from django.test import TestCase
from django.core.files.uploadedfile import SimpleUploadedFile

from orgs.models import Organization
from public_frontend.models import Lead
from .models import Document
from .controllers.pickup_request import PickupRequestController, PickupRequestData


class PickupRequestControllerTests(TestCase):
    def setUp(self) -> None:
        self.org = Organization.objects.create(name="Test Org", code="TEST")
        self.ctrl = PickupRequestController()

    def test_submit_without_files_creates_lead_only(self):
        data = PickupRequestData(
            organization=self.org,
            name="Alice",
            email="alice@example.com",
            phone="+1 555 0000",
            address="123 Road",
            materials="PET bottles",
            preferred_at=None,
            files=[],
        )

        result = self.ctrl.submit(data)
        self.assertTrue(result.ok)
        self.assertIsNotNone(result.lead_id)
        self.assertEqual(result.document_ids, [])

        lead = Lead.objects.get(pk=result.lead_id)
        self.assertEqual(lead.organization, self.org)
        self.assertEqual(lead.name, "Alice")
        self.assertEqual(lead.subject, "Pickup Request")
        self.assertEqual(lead.source, "pickup_request")

        self.assertEqual(Document.objects.filter(object_id=lead.id).count(), 0)

    def test_submit_with_files_creates_documents(self):
        file1 = SimpleUploadedFile("photo1.jpg", b"fakejpegdata1", content_type="image/jpeg")
        file2 = SimpleUploadedFile("photo2.jpg", b"fakejpegdata2", content_type="image/jpeg")

        data = PickupRequestData(
            organization=self.org,
            name="Bob",
            email="bob@example.com",
            phone="+1 555 1111",
            address="456 Avenue",
            materials="Aluminum cans",
            preferred_at=None,
            files=[file1, file2],
        )

        result = self.ctrl.submit(data)
        self.assertTrue(result.ok)
        self.assertIsNotNone(result.lead_id)
        self.assertEqual(len(result.document_ids), 2)

        lead = Lead.objects.get(pk=result.lead_id)
        docs = Document.objects.filter(object_id=lead.id).order_by("id")
        self.assertEqual(docs.count(), 2)
        for d in docs:
            self.assertEqual(d.organization, self.org)
            self.assertEqual(d.kind, "pickup_request")
            self.assertEqual(d.content_object, lead)
