"""Agent-composed outbound email.

This code sends real mail to real customers from a client's own mailbox, so the
rules worth pinning are the ones whose failure is visible outside the CRM:

  * a tenant must not be able to send as another tenant's mailbox
  * the read-only oversight role must not be able to email a customer at all
  * the outbound leg must NOT open a ticket -- the ticket appears only when the
    customer replies, and that reply must link back to the email that caused it
"""
from unittest.mock import patch

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

from clients.models import Client, ClientEmailAccount, OutboundEmail
from clients.views import OutboundEmailViewSet
from clients.management.commands import fetch_emails as fe
from core.models import Role, User
from tickets.models import Ticket

from .tests import build_email


def role(name):
    return Role.objects.get_or_create(name=name)[0]


class OutboundEmailTests(TestCase):
    def setUp(self):
        self.factory = APIRequestFactory()

        self.acme = Client.objects.create(name='Acme', code='ACME', is_active=True)
        self.other = Client.objects.create(name='Globex', code='GLBX', is_active=True)

        self.acme_box = ClientEmailAccount.objects.create(
            client=self.acme, name='Support', email='support@acme.test',
            smtp_host='smtp.acme.test', smtp_port='587', smtp_pass='pw', is_active=True)
        self.other_box = ClientEmailAccount.objects.create(
            client=self.other, name='Support', email='support@globex.test',
            smtp_host='smtp.globex.test', smtp_port='587', smtp_pass='pw', is_active=True)

        # A client-portal agent belonging to Acme.
        self.portal_agent = User.objects.create_user(
            username='acme_agent', password='x', client=self.acme,
            role=role('client_agent'), first_name='Ann', last_name='Agent')
        # Internal staff -- sees every client.
        self.staff = User.objects.create_user(
            username='staff', password='x', role=role('operations_manager'))
        # Oversight account: reads everything, must never send.
        self.sysadmin = User.objects.create_user(
            username='sysadmin', password='x', role=role('system_admin'))

    # -- helpers ----------------------------------------------------------
    def send_as(self, user, **payload):
        req = self.factory.post('/api/outbound-emails/', payload, format='json')
        force_authenticate(req, user=user)
        return OutboundEmailViewSet.as_view({'post': 'create'})(req)

    def valid_payload(self, **over):
        data = dict(account=self.acme_box.id, to_emails='cust1@example.com',
                    subject='Your refund', body='It cleared today.')
        data.update(over)
        return data

    # -- sending ----------------------------------------------------------
    @patch('core.outbound.send_outbound_email', return_value='<out-1@acme.test>')
    def test_send_records_sent_row(self, mock_send):
        resp = self.send_as(self.portal_agent, **self.valid_payload())
        self.assertEqual(resp.status_code, 201, resp.data)
        row = OutboundEmail.objects.get()
        self.assertEqual(row.status, OutboundEmail.SENT)
        self.assertEqual(row.message_id, '<out-1@acme.test>')
        self.assertEqual(row.client, self.acme)
        self.assertEqual(row.sender, self.portal_agent)
        self.assertIsNotNone(row.sent_at)
        self.assertTrue(mock_send.called)

    @patch('core.outbound.send_outbound_email', return_value='<out-1@acme.test>')
    def test_outbound_does_not_create_a_ticket(self, _mock):
        """The outbound leg ends at the customer. The ticket comes from the reply."""
        self.send_as(self.portal_agent, **self.valid_payload())
        self.assertEqual(Ticket.objects.count(), 0)

    @patch('core.outbound.send_outbound_email', side_effect=Exception('smtp refused'))
    def test_failed_send_is_recorded_with_the_error(self, _mock):
        resp = self.send_as(self.portal_agent, **self.valid_payload())
        self.assertEqual(resp.status_code, 400)
        row = OutboundEmail.objects.get()
        self.assertEqual(row.status, OutboundEmail.FAILED)
        self.assertIn('smtp refused', row.error)

    @patch('core.outbound.send_outbound_email', return_value='<x@y>')
    def test_agent_name_is_used_but_reply_to_stays_the_shared_mailbox(self, mock_send):
        self.send_as(self.portal_agent, **self.valid_payload())
        kwargs = mock_send.call_args.kwargs
        self.assertIn('Ann Agent', kwargs['from_name'])

    # -- tenant isolation -------------------------------------------------
    @patch('core.outbound.send_outbound_email', return_value='<x@y>')
    def test_cannot_send_from_another_clients_mailbox(self, mock_send):
        resp = self.send_as(self.portal_agent,
                            **self.valid_payload(account=self.other_box.id))
        self.assertEqual(resp.status_code, 403)
        self.assertFalse(mock_send.called)
        self.assertEqual(OutboundEmail.objects.count(), 0)

    @patch('core.outbound.send_outbound_email', return_value='<x@y>')
    def test_readonly_admin_cannot_email_a_customer(self, mock_send):
        resp = self.send_as(self.sysadmin, **self.valid_payload())
        self.assertEqual(resp.status_code, 403)
        self.assertFalse(mock_send.called)
        self.assertEqual(OutboundEmail.objects.count(), 0)

    def test_sent_log_is_scoped_to_the_callers_client(self):
        OutboundEmail.objects.create(client=self.acme, account=self.acme_box,
                                     to_emails='a@x.test', subject='A', body='b',
                                     status=OutboundEmail.SENT)
        OutboundEmail.objects.create(client=self.other, account=self.other_box,
                                     to_emails='b@x.test', subject='B', body='b',
                                     status=OutboundEmail.SENT)
        req = self.factory.get('/api/outbound-emails/')
        force_authenticate(req, user=self.portal_agent)
        resp = OutboundEmailViewSet.as_view({'get': 'list'})(req)
        rows = resp.data['results'] if isinstance(resp.data, dict) else resp.data
        subjects = {r['subject'] for r in rows}
        self.assertEqual(subjects, {'A'})

    def test_mailboxes_endpoint_excludes_other_tenants(self):
        req = self.factory.get('/api/outbound-emails/mailboxes/')
        force_authenticate(req, user=self.portal_agent)
        resp = OutboundEmailViewSet.as_view({'get': 'mailboxes'})(req)
        emails = {m['email'] for m in resp.data['mailboxes']}
        self.assertEqual(emails, {'support@acme.test'})
        self.assertTrue(resp.data['can_send'])

    def test_mailboxes_endpoint_tells_readonly_admin_it_cannot_send(self):
        req = self.factory.get('/api/outbound-emails/mailboxes/')
        force_authenticate(req, user=self.sysadmin)
        resp = OutboundEmailViewSet.as_view({'get': 'mailboxes'})(req)
        self.assertFalse(resp.data['can_send'])

    # -- validation -------------------------------------------------------
    @patch('core.outbound.send_outbound_email', return_value='<x@y>')
    def test_rejects_a_malformed_recipient(self, mock_send):
        resp = self.send_as(self.portal_agent,
                            **self.valid_payload(to_emails='not-an-address'))
        self.assertEqual(resp.status_code, 400)
        self.assertFalse(mock_send.called)

    @patch('core.outbound.send_outbound_email', return_value='<x@y>')
    def test_rejects_empty_body(self, mock_send):
        resp = self.send_as(self.portal_agent, **self.valid_payload(body='   '))
        self.assertEqual(resp.status_code, 400)
        self.assertFalse(mock_send.called)

    @patch('core.outbound.send_outbound_email', return_value='<x@y>')
    def test_refuses_a_mailbox_with_no_smtp_password(self, mock_send):
        self.acme_box.smtp_pass = ''
        self.acme_box.save(update_fields=['smtp_pass'])
        resp = self.send_as(self.portal_agent, **self.valid_payload())
        self.assertEqual(resp.status_code, 400)
        self.assertIn('SMTP', str(resp.data['error']))
        self.assertFalse(mock_send.called)


class OutboundReplyLinkTests(TestCase):
    """The customer's reply must come back as a ticket tied to the outbound mail."""

    def setUp(self):
        self.client_obj = Client.objects.create(name='Acme', code='ACME', is_active=True)
        self.acct = ClientEmailAccount.objects.create(
            client=self.client_obj, name='Support', email='support@acme.test',
            imap_host='imap.test', imap_pass='x',
            smtp_host='smtp.test', smtp_pass='x', is_active=True)
        self.agent = User.objects.create_user(
            username='ann', password='x', client=self.client_obj, role=role('client_agent'))
        self.outbound = OutboundEmail.objects.create(
            client=self.client_obj, account=self.acct, sender=self.agent,
            to_emails='cust1@example.com', subject='Your refund',
            body='It cleared today.', status=OutboundEmail.SENT,
            message_id='<out-1@acme.test>')
        self.results = {'created': 0, 'threaded': 0, 'skipped': 0,
                        'duplicates': 0, 'errors': []}

    def ingest(self, raw):
        fe.process_message(self.acct, raw, self.results)

    @patch('ai_services.auto_reply.auto_reply_to_ticket')
    def test_reply_opens_a_ticket_linked_to_the_outbound_email(self, _ar):
        self.ingest(build_email('Re: Your refund', 'cust1@example.com',
                                body='Thanks, got it.', msgid='<r1@example.com>',
                                in_reply_to='<out-1@acme.test>'))
        self.assertEqual(self.results['created'], 1)
        ticket = Ticket.objects.get()
        self.outbound.refresh_from_db()
        self.assertEqual(self.outbound.ticket, ticket)

    @patch('ai_services.auto_reply.auto_reply_to_ticket')
    def test_reply_is_assigned_to_the_agent_who_started_the_thread(self, _ar):
        self.ingest(build_email('Re: Your refund', 'cust1@example.com',
                                msgid='<r1@example.com>',
                                in_reply_to='<out-1@acme.test>'))
        self.assertEqual(Ticket.objects.get().assigned_agent, self.agent)

    @patch('ai_services.auto_reply.auto_reply_to_ticket')
    def test_unrelated_email_does_not_claim_the_outbound_row(self, _ar):
        self.ingest(build_email('Something else', 'someone@example.com',
                                msgid='<r2@example.com>'))
        self.outbound.refresh_from_db()
        self.assertIsNone(self.outbound.ticket)
