from django.test import TestCase
from django.core import mail
from unittest.mock import patch, MagicMock
from backend.core.models import Organization, Document
from backend.accounts.models import EmailConfirmation
from backend.core.utils import generate_first_page_image
from backend.accounts.utils import send_confirmation_email, send_payment_email, send_document_email
import uuid
from django.utils.timezone import now

class EmailTests(TestCase):
    def setUp(self):
        self.email = "test@example.com"
        self.organization = Organization.objects.create(
            id=1,
            name="Test Organization",
            email="test@example.com",
            employee_headcount="100-500",
            annual_revenue="$1M-$10M",
            critical_applications="5-10",
            compliance_frameworks=["Ab", "Ba"],
            industry_sector="Technology",
            it_dependency=8,
            data_sensitivity="High",
            network_infrastructure="Cloud-based",
            remote_workforce_percentage="50%",
            third_party_vendor_access="10-20",
            internal_software_development="Moderate",
            geographic_scope="Global",
            customer_base="Enterprise",
            customer_type="B2B",
            product_portfolio="Diverse",
            supplier_base="International",
            it_infrastructure=["Cloud", "On-Premise"],
            intellectual_property=["Patents", "Trademarks"],
            sensitive_data=["PII", "Financial Data"],
            integration_level="Highly Integrated"
        )
        self.document = Document.objects.create(organization=self.organization)
        
    @patch("backend.accounts.utils.send_mail")
    def test_send_confirmation_email(self, mock_send_mail):
        confirmation = EmailConfirmation.objects.create(email=self.email, uuid=uuid.uuid4(), created_at=now())
        send_confirmation_email(self.email)
        
        confirmation.refresh_from_db()
        self.assertIsNotNone(confirmation.uuid)
        self.assertEqual(mock_send_mail.call_count, 1)

    @patch("backend.accounts.utils.send_mail")
    def test_send_payment_email(self, mock_send_mail):
        send_payment_email(self.email)
        self.assertEqual(mock_send_mail.call_count, 1)

    @patch("backend.accounts.utils.EmailMultiAlternatives.send")
    @patch("backend.accounts.utils.generate_first_page_image")
    def test_send_document_email(self, mock_generate_image, mock_send):
        mock_image_io = MagicMock()
        mock_image_io.getvalue.return_value = b"fake image data"
        mock_generate_image.return_value = mock_image_io
        
        document_link = "https://example.com/document.pdf"
        send_document_email(self.email, document_link, self.document)
        
        mock_generate_image.assert_called_once_with(self.document)
        mock_send.assert_called_once()
