"""Client portal invitations.

The invitation is how a client gets their first login, so the rule that matters
is: a mail problem must never stop an admin from onboarding a client. The row
and its register_url are created before any mail is attempted and returned
whatever happens, so the link can always be copied by hand.

Production had this backwards -- Django's SMTP settings pointed at an
unconfigured host with no EMAIL_TIMEOUT, so send_mail hung until the gateway
killed the request and the admin saw only "Failed to send invitation."
"""
from unittest.mock import patch

from django.test import TestCase
from rest_framework.test import APIRequestFactory, force_authenticate

from clients.models import Client, ClientEmailAccount
from core.models import Role, User, ClientInvitation
from core.views import ClientInviteView


class ClientInviteTests(TestCase):
    def setUp(self):
        self.factory = APIRequestFactory()
        self.client_obj = Client.objects.create(name='NAIA-crm', code='NA2026', is_active=True)
        self.admin = User.objects.create_user(
            username='admin', password='x',
            role=Role.objects.get_or_create(name='system_admin')[0])

    def invite(self, email='ops@naia.test', client_id=None):
        req = self.factory.post('/api/auth/client-invite/', {
            'client_id': client_id or self.client_obj.id, 'email': email,
        }, format='json')
        force_authenticate(req, user=self.admin)
        return ClientInviteView.as_view()(req)

    def add_mailbox(self, **over):
        data = dict(client=self.client_obj, name='Support', email='support@naia.test',
                    smtp_host='smtp.naia.test', smtp_port='587', smtp_pass='pw',
                    is_active=True)
        data.update(over)
        return ClientEmailAccount.objects.create(**data)

    # -- the bug that was reported -------------------------------------
    @patch('core.views.send_mail', side_effect=Exception('Connection timed out'))
    def test_invitation_still_created_when_all_mail_fails(self, _m):
        """This is the reported failure: no mailbox, global SMTP broken."""
        resp = self.invite()
        self.assertEqual(resp.status_code, 201)
        self.assertFalse(resp.data['email_sent'])
        # The admin can still onboard the client by hand.
        self.assertIn('client-register?token=', resp.data['register_url'])
        self.assertEqual(ClientInvitation.objects.count(), 1)

    @patch('core.views.send_mail', side_effect=Exception('Connection timed out'))
    def test_failure_reason_is_reported_not_swallowed(self, _m):
        resp = self.invite()
        self.assertIn('Connection timed out', resp.data['email_error'])

    # -- preferred path: the client's own working mailbox ---------------
    @patch('core.outbound.send_outbound_email', return_value='<i@x>')
    def test_uses_the_clients_own_mailbox_when_available(self, mock_send):
        self.add_mailbox()
        resp = self.invite()
        self.assertEqual(resp.status_code, 201)
        self.assertTrue(resp.data['email_sent'])
        self.assertTrue(mock_send.called)
        self.assertEqual(mock_send.call_args.kwargs['to'], 'ops@naia.test')

    @patch('core.views.send_mail')
    @patch('core.outbound.send_outbound_email', return_value='<i@x>')
    def test_default_mailer_is_not_used_when_the_mailbox_worked(self, _ob, mock_django):
        self.add_mailbox()
        self.invite()
        self.assertFalse(mock_django.called)

    @patch('core.views.send_mail')
    @patch('core.outbound.send_outbound_email', side_effect=Exception('auth failed'))
    def test_falls_back_to_default_mailer_when_the_mailbox_fails(self, _ob, mock_django):
        self.add_mailbox()
        resp = self.invite()
        self.assertTrue(mock_django.called)
        self.assertTrue(resp.data['email_sent'])

    @patch('core.views.send_mail')
    @patch('core.outbound.send_outbound_email', return_value='<i@x>')
    def test_ignores_a_mailbox_with_no_smtp_password(self, mock_ob, mock_django):
        self.add_mailbox(smtp_pass='')
        self.invite()
        self.assertFalse(mock_ob.called)
        self.assertTrue(mock_django.called)

    # -- unchanged behaviour --------------------------------------------
    @patch('core.views.send_mail')
    def test_previous_unused_invitations_are_expired(self, _m):
        self.invite()
        self.invite()
        self.assertEqual(ClientInvitation.objects.count(), 2)
        self.assertEqual(
            ClientInvitation.objects.filter(is_used=False, expires_at__gt=__import__(
                'django.utils.timezone', fromlist=['timezone']).now()).count(), 1)

    def test_non_admin_is_refused(self):
        agent = User.objects.create_user(
            username='agent', password='x',
            role=Role.objects.get_or_create(name='agent')[0])
        req = self.factory.post('/api/auth/client-invite/', {
            'client_id': self.client_obj.id, 'email': 'x@y.test'}, format='json')
        force_authenticate(req, user=agent)
        resp = ClientInviteView.as_view()(req)
        self.assertEqual(resp.status_code, 403)
        self.assertEqual(ClientInvitation.objects.count(), 0)
