"""Email ingestion tests: threading, deduplication, attachments, SLA.

Threading is the fragile part of this system — it decides whether two unrelated
customers land in one ticket. That has gone wrong in production before, so the
rules are pinned here.
"""
from email.message import EmailMessage

from django.test import TestCase

from clients.management.commands import fetch_emails as fe
from clients.models import Client, ClientEmailAccount
from sla.models import SLAPolicy
from tickets.models import Ticket, TicketAttachment, TicketComment


def build_email(subject, from_addr, body='hello', msgid='<a@x>',
                in_reply_to=None, attachments=()):
    msg = EmailMessage()
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = 'support@acme.test'
    msg['Message-ID'] = msgid
    if in_reply_to:
        msg['In-Reply-To'] = in_reply_to
        msg['References'] = in_reply_to
    msg.set_content(body)
    for filename, data, (maintype, subtype) in attachments:
        msg.add_attachment(data, maintype=maintype, subtype=subtype, filename=filename)
    return msg.as_bytes()


class IngestionTests(TestCase):
    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_user='support@acme.test', imap_pass='x',
            smtp_host='smtp.test', smtp_user='support@acme.test', smtp_pass='x',
            is_active=True)
        self.results = {'created': 0, 'threaded': 0, 'skipped': 0,
                        'duplicates': 0, 'errors': []}

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

    # ---- deduplication ----------------------------------------------------

    def test_same_message_twice_creates_one_ticket(self):
        raw = build_email('Order help', 'marc@example.com', msgid='<dup@x>')
        self.ingest(raw)
        self.ingest(raw)
        self.assertEqual(Ticket.objects.count(), 1)

    # ---- threading --------------------------------------------------------

    def test_reply_headers_thread_onto_the_same_ticket(self):
        self.ingest(build_email('Order help', 'marc@example.com', msgid='<first@x>'))
        self.ingest(build_email('Re: Order help', 'marc@example.com',
                                msgid='<second@x>', in_reply_to='<first@x>'))
        self.assertEqual(Ticket.objects.count(), 1)
        self.assertEqual(TicketComment.objects.filter(comment_type='customer_reply').count(), 1)

    def test_different_senders_never_share_a_ticket(self):
        """Same subject, two people. These must not merge — this exact case
        produced three customers in one ticket in production."""
        self.ingest(build_email('ORDER', 'marc@example.com', msgid='<m1@x>'))
        self.ingest(build_email('ORDER', 'someone.else@example.com', msgid='<s1@x>'))
        self.assertEqual(Ticket.objects.count(), 2)

    def test_same_sender_new_subject_opens_a_new_ticket(self):
        self.ingest(build_email('Order help', 'marc@example.com', msgid='<n1@x>'))
        self.ingest(build_email('Refund please', 'marc@example.com', msgid='<n2@x>'))
        self.assertEqual(Ticket.objects.count(), 2)

    # ---- attachments ------------------------------------------------------

    def test_attachment_is_saved(self):
        raw = build_email(
            'Screenshot attached', 'marc@example.com', msgid='<att@x>',
            attachments=[('screenshot.png', b'\x89PNG fake', ('image', 'png'))])
        self.ingest(raw)
        att = TicketAttachment.objects.get()
        self.assertEqual(att.filename, 'screenshot.png')
        self.assertEqual(att.tags, 'inbound-email')
        self.assertGreater(att.file_size, 0)

    def test_executable_attachment_is_refused(self):
        raw = build_email(
            'Invoice', 'marc@example.com', msgid='<exe@x>',
            attachments=[('invoice.pdf.exe', b'MZ', ('application', 'octet-stream'))])
        self.ingest(raw)
        self.assertEqual(TicketAttachment.objects.count(), 0)

    def test_attachment_filename_cannot_escape_the_upload_directory(self):
        raw = build_email(
            'Traversal', 'marc@example.com', msgid='<trav@x>',
            attachments=[('../../../etc/passwd', b'root:x:0:0', ('text', 'plain'))])
        self.ingest(raw)
        att = TicketAttachment.objects.get()
        self.assertEqual(att.filename, 'passwd')
        self.assertNotIn('..', att.file.name)

    # ---- SLA --------------------------------------------------------------

    def test_matching_sla_policy_sets_due_dates(self):
        SLAPolicy.objects.create(
            client=self.client_obj, name='Urgent', priority='critical',
            category='general', first_response_minutes=30, resolution_minutes=240,
            is_active=True)
        self.ingest(build_email('URGENT: system down', 'marc@example.com', msgid='<sla@x>'))
        t = Ticket.objects.get()
        self.assertIsNotNone(t.sla_policy)
        self.assertIsNotNone(t.first_response_due)
        self.assertIsNotNone(t.resolution_due)
        self.assertGreater(t.resolution_due, t.first_response_due)

    def test_ticket_survives_when_no_policy_matches(self):
        self.ingest(build_email('Just a question', 'marc@example.com', msgid='<nosla@x>'))
        t = Ticket.objects.get()
        self.assertIsNone(t.sla_policy)
