from uuid import uuid4

from app_new.extensions import db
from app_new.core.models.maintenance import WatchdogLog
from app_new.outlook.models import OutlookAccount, OutlookFolder, OutlookMail


class _OutlookResponse:
    status_code = 200

    def __init__(self, messages):
        self._messages = messages

    def json(self):
        return {'value': self._messages}


def _message(message_id, subject, body):
    return {
        'Id': message_id,
        'Subject': subject,
        'From': {'EmailAddress': {'Name': 'Expéditeur', 'Address': 'sender@example.test'}},
        'ReceivedDateTime': '2026-08-14T10:00:00Z',
        'IsRead': False,
        'HasAttachments': False,
        'BodyPreview': body[:200],
        'Body': {'Content': body, 'ContentType': 'HTML'},
        'ToRecipients': [], 'CcRecipients': [], 'Importance': 'normal',
    }


def test_outlook_sync_stores_large_body_and_logs_only_bad_message(
        authenticated_client, app, admin_user, monkeypatch):
    with app.app_context():
        account = OutlookAccount(user_id=admin_user['id'], email='sync@example.test', tenant_id='test')
        folder = OutlookFolder(
            id=f'folder-{uuid4().hex}', account=account, name='Inbox',
            display_name='Boîte de réception', folder_type='inbox',
        )
        db.session.add_all([account, folder]); db.session.commit()
        account_id, folder_id = account.id, folder.id

        large_body = '<p>' + ('Contenu volumineux ' * 7000) + '</p>'
        confidential_bad_body = 'SECRET_BODY_' * 100
        messages = [
            _message('X' * 600, 'Message invalide', confidential_bad_body),
            _message(f'mail-{uuid4().hex}', 'Grand message valide', large_body),
        ]
        monkeypatch.setattr('app_new.outlook.sync.get_access_token', lambda unused: ('token', None))
        monkeypatch.setattr('requests.get', lambda *args, **kwargs: _OutlookResponse(messages))

        response = authenticated_client.post(
            f'/outlook/api/sync-mails/{account_id}/{folder_id}?max=20'
        )
        assert response.status_code == 200
        payload = response.get_json()
        assert payload['new'] == 1
        assert payload['skipped'] == 1

        stored = OutlookMail.query.filter_by(account_id=account_id, subject='Grand message valide').one()
        assert len(stored.body_content.encode('utf-8')) > 65535
        log = WatchdogLog.query.filter_by(watchdog_name='outlook_sync', level='error').one()
        assert 'Message invalide' in log.message
        assert 'SECRET_BODY' not in log.message

        OutlookMail.query.filter_by(account_id=account_id).delete(synchronize_session=False)
        OutlookFolder.query.filter_by(account_id=account_id).delete(synchronize_session=False)
        OutlookAccount.query.filter_by(id=account_id).delete(synchronize_session=False)
        WatchdogLog.query.filter_by(id=log.id).delete(synchronize_session=False)
        db.session.commit()
