import uuid
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from .document_types import DocumentType
from .document_versions import DocumentVersion


class DocumentDeliveryChannel(models.Model):
    """Company-scoped Email, WhatsApp, Portal, Print, and Cloud integration channels (encrypted secrets)."""

    class ChannelType(models.TextChoices):
        EMAIL = "EMAIL", "Email (SMTP / Provider)"
        WHATSAPP = "WHATSAPP", "WhatsApp Business Messaging"
        PORTAL = "PORTAL", "Customer Portal Link"
        PHYSICAL_PRINT = "PHYSICAL_PRINT", "Physical Print Queue"
        CLOUD_ARCHIVE = "CLOUD_ARCHIVE", "Cloud Storage Archive"
        WEBHOOK_API = "WEBHOOK_API", "External API Webhook"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.CASCADE, related_name="document_delivery_channels"
    )
    channel_type = models.CharField(max_length=20, choices=ChannelType.choices)
    name = models.CharField(max_length=120)
    is_enabled = models.BooleanField(default=True)
    sender_identity = models.CharField(max_length=160, blank=True)
    endpoint_or_host = models.CharField(max_length=255, blank=True)
    port = models.PositiveIntegerField(null=True, blank=True)
    use_tls = models.BooleanField(default=True)
    encrypted_credentials = models.TextField(blank=True)
    default_subject_template = models.CharField(max_length=200, blank=True)
    default_body_template = models.TextField(blank=True)
    max_attachment_mb = models.PositiveSmallIntegerField(default=10)
    config_json = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "document_delivery_channels"
        unique_together = [("company", "channel_type", "name")]
        ordering = ["channel_type", "name"]


class DocumentDeliveryRule(models.Model):
    """Event-driven & scheduled automatic document generation and distribution rules."""

    class EventTrigger(models.TextChoices):
        SALES_INVOICE_APPROVED = "SALES_INVOICE_APPROVED", "Sales Invoice Approved"
        DELIVERY_DISPATCHED = "DELIVERY_DISPATCHED", "Delivery Dispatched"
        GOODS_RECEIVED = "GOODS_RECEIVED", "Goods Received (GRN)"
        PO_APPROVED = "PO_APPROVED", "Purchase Order Approved"
        JOB_WORK_COMPLETED = "JOB_WORK_COMPLETED", "Job Work Completed"
        LOAN_REPAYMENT_POSTED = "LOAN_REPAYMENT_POSTED", "Loan Repayment Posted"
        MONTHLY_SCHEDULED_REPORT = "MONTHLY_SCHEDULED_REPORT", "Monthly Scheduled Report"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.CASCADE, related_name="document_delivery_rules"
    )
    document_type = models.ForeignKey(DocumentType, on_delete=models.CASCADE)
    channel = models.ForeignKey(DocumentDeliveryChannel, on_delete=models.CASCADE)
    event_trigger = models.CharField(max_length=32, choices=EventTrigger.choices)
    auto_generate_pdf = models.BooleanField(default=True)
    auto_send = models.BooleanField(default=False)
    require_recipient_consent = models.BooleanField(default=True)
    cc_emails = models.JSONField(default=list, blank=True, encoder=DjangoJSONEncoder)
    bcc_emails = models.JSONField(default=list, blank=True, encoder=DjangoJSONEncoder)
    cron_expression = models.CharField(max_length=64, blank=True)
    is_active = models.BooleanField(default=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "document_delivery_rules"


class DocumentDeliveryLog(models.Model):
    """Lifecycle delivery tracker: Generated -> Queued -> Sent -> Delivered -> Viewed -> Downloaded."""

    class Status(models.TextChoices):
        GENERATED = "GENERATED", "Generated"
        QUEUED = "QUEUED", "Queued"
        SENT = "SENT", "Sent"
        DELIVERED = "DELIVERED", "Delivered"
        VIEWED = "VIEWED", "Viewed"
        DOWNLOADED = "DOWNLOADED", "Downloaded"
        FAILED = "FAILED", "Failed"
        CANCELLED = "CANCELLED", "Cancelled"
        EXPIRED = "EXPIRED", "Expired"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.CASCADE, related_name="document_delivery_logs"
    )
    document_version = models.ForeignKey(
        DocumentVersion, on_delete=models.CASCADE, related_name="delivery_logs"
    )
    channel = models.ForeignKey(
        DocumentDeliveryChannel, on_delete=models.SET_NULL, null=True, blank=True
    )
    channel_type = models.CharField(max_length=20)
    recipient = models.CharField(max_length=180)
    subject = models.CharField(max_length=200, blank=True)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.GENERATED, db_index=True)
    provider_message_id = models.CharField(max_length=128, blank=True)
    retry_count = models.PositiveSmallIntegerField(default=0)
    failure_reason = models.TextField(blank=True)
    timeline = models.JSONField(default=list, blank=True, encoder=DjangoJSONEncoder)
    dispatched_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "document_delivery_logs"
        ordering = ["-created_at"]


class DocumentShareLink(models.Model):
    """Expiring secure portal download token bound strictly to one DocumentVersion."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    document_version = models.ForeignKey(
        DocumentVersion, on_delete=models.CASCADE, related_name="share_links"
    )
    token_hash = models.CharField(max_length=64, unique=True, db_index=True)
    recipient_hint = models.CharField(max_length=160, blank=True)
    expires_at = models.DateTimeField()
    max_downloads = models.PositiveSmallIntegerField(default=10)
    download_count = models.PositiveSmallIntegerField(default=0)
    is_revoked = models.BooleanField(default=False)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "document_share_links"
        ordering = ["-created_at"]


class DocumentAuditLog(models.Model):
    """Append-only print, export, share, template publish, and archive audit trail."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.PROTECT, related_name="document_audit_logs"
    )
    actor = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="document_audit_logs"
    )
    action = models.CharField(max_length=48, db_index=True)
    document_type_code = models.CharField(max_length=64, db_index=True)
    source_id = models.CharField(max_length=100, blank=True)
    document_number = models.CharField(max_length=64, blank=True)
    output_format = models.CharField(max_length=16, blank=True)
    details = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    ip_address = models.GenericIPAddressField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

    class Meta:
        db_table = "document_audit_logs"
        ordering = ["-created_at"]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            raise PermissionError("DocumentAuditLog records are append-only.")
        return super().save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        raise PermissionError("DocumentAuditLog records cannot be deleted.")

