import uuid
from django.conf import settings
from django.core.serializers.json import DjangoJSONEncoder
from django.db import models
from django.utils import timezone


def default_auto_dismiss_ms() -> dict:
    return {
        "SUCCESS": 4000,
        "INFO": 5000,
        "WARNING": 0,
        "ERROR": 0,
        "CONFIRM": 0,
        "CRITICAL": 0,
    }


class NotificationEvent(models.Model):
    """Transactional outbox record for domain events so notifications survive broker/WS downtime."""

    class ProcessingStatus(models.TextChoices):
        PENDING = "PENDING", "Pending"
        PROCESSED = "PROCESSED", "Processed"
        FAILED = "FAILED", "Failed"

    event_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    event_type = models.CharField(max_length=96, db_index=True)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, null=True, blank=True, related_name="notification_events")
    actor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="triggered_notification_events")
    source_object_type = models.CharField(max_length=64, blank=True)
    source_object_id = models.CharField(max_length=64, blank=True)
    source_reference = models.CharField(max_length=128, blank=True)
    dedup_key = models.CharField(max_length=191, blank=True, db_index=True)
    payload = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    processed_at = models.DateTimeField(null=True, blank=True)
    processing_status = models.CharField(max_length=16, choices=ProcessingStatus.choices, default=ProcessingStatus.PENDING, db_index=True)
    error_detail = models.CharField(max_length=255, blank=True)

    class Meta:
        db_table = "notif_events"
        ordering = ["-created_at"]
        indexes = [
            models.Index(fields=["company", "event_type", "created_at"]),
        ]


class Notification(models.Model):
    class Priority(models.TextChoices):
        CRITICAL = "CRITICAL", "Critical"
        HIGH = "HIGH", "High"
        NORMAL = "NORMAL", "Normal"
        LOW = "LOW", "Low"

    class Category(models.TextChoices):
        GENERAL = "GENERAL", "General"
        MESSAGE = "MESSAGE", "Chat & Messages"
        APPROVAL = "APPROVAL", "Tasks & Approvals"
        SYSTEM = "SYSTEM", "System & Updates"
        SECURITY = "SECURITY", "Security & Audit"
        BACKUP = "BACKUP", "Backup & Recovery"
        ACCOUNTING = "ACCOUNTING", "Accounting & Vouchers"
        BANKING = "BANKING", "Banking & Treasury"
        PARTY_HUB = "PARTY_HUB", "AP / AR"
        PROJECT = "PROJECT", "Projects & Sites"
        HR = "HR", "HR & Payroll"
        REPORTS = "REPORTS", "Reports"

    class Status(models.TextChoices):
        ACTIVE = "ACTIVE", "Active"
        STALE = "STALE", "Stale (Source Updated)"
        EXECUTED = "EXECUTED", "Action Executed"
        EXPIRED = "EXPIRED", "Expired"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, null=True, blank=True, related_name="notifications")
    recipient = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="notifications")
    sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="sent_notifications")
    branch = models.ForeignKey("tenancy.Branch", on_delete=models.SET_NULL, null=True, blank=True)
    department = models.ForeignKey("accounting.Department", on_delete=models.SET_NULL, null=True, blank=True)
    event = models.ForeignKey(NotificationEvent, on_delete=models.SET_NULL, null=True, blank=True, related_name="notifications")
    event_type = models.CharField(max_length=96, db_index=True)
    title = models.CharField(max_length=180)
    message = models.TextField()
    description = models.TextField(blank=True)
    priority = models.CharField(max_length=16, choices=Priority.choices, default=Priority.NORMAL, db_index=True)
    category = models.CharField(max_length=24, choices=Category.choices, default=Category.GENERAL, db_index=True)
    module = models.CharField(max_length=48, default="SYSTEM", db_index=True)
    popup_kind = models.CharField(max_length=24, default="INFO")  # SUCCESS|ERROR|WARNING|INFO|CONFIRM|CRITICAL|PROCESSING|CHAT
    source_object_type = models.CharField(max_length=64, blank=True)
    source_object_id = models.CharField(max_length=64, blank=True)
    source_reference = models.CharField(max_length=128, blank=True)
    route_key = models.CharField(max_length=128, blank=True)
    action_definition = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    metadata = models.JSONField(default=dict, blank=True, encoder=DjangoJSONEncoder)
    dedup_key = models.CharField(max_length=191, null=True, blank=True, db_index=True)
    is_mandatory_critical = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)
    expires_at = models.DateTimeField(null=True, blank=True)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.ACTIVE, db_index=True)

    class Meta:
        db_table = "notif_notifications"
        ordering = ["-created_at"]
        indexes = [
            models.Index(fields=["company", "recipient", "status", "-created_at"], name="idx_notif_rec_st_dt"),
        ]
        unique_together = [("company", "recipient", "dedup_key")]
        indexes = [
            models.Index(fields=["recipient", "company", "created_at"]),
            models.Index(fields=["recipient", "category", "status"]),
            models.Index(fields=["source_object_type", "source_object_id"]),
        ]


class NotificationRecipientState(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    notification = models.OneToOneField(Notification, on_delete=models.CASCADE, related_name="state")
    recipient = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="notification_states")
    is_read = models.BooleanField(default=False, db_index=True)
    read_at = models.DateTimeField(null=True, blank=True)
    is_archived = models.BooleanField(default=False, db_index=True)
    archived_at = models.DateTimeField(null=True, blank=True)
    dismissed_at = models.DateTimeField(null=True, blank=True)
    acknowledged_at = models.DateTimeField(null=True, blank=True)
    executed_action = models.CharField(max_length=64, blank=True)
    executed_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        db_table = "notif_recipient_states"
        indexes = [
            models.Index(fields=["recipient", "is_read", "is_archived"]),
        ]


class NotificationPreference(models.Model):
    """Per-user global ('ALL') and per-module notification & popup preferences."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="notification_preferences")
    category = models.CharField(max_length=32, default="ALL")  # ALL|ACCOUNTING|BANKING|PARTY_HUB|PROJECT|PROCUREMENT|INVENTORY|HR|REPORTS|CHAT|SYSTEM|SECURITY
    popup_enabled = models.BooleanField(default=True)
    center_screen_enabled = models.BooleanField(default=True)
    sound_enabled = models.BooleanField(default=True)
    desktop_enabled = models.BooleanField(default=False)
    grouping_enabled = models.BooleanField(default=True)
    badge_enabled = models.BooleanField(default=True)
    history_enabled = models.BooleanField(default=True)
    message_preview = models.BooleanField(default=True)
    delivery_mode = models.CharField(max_length=24, default="IMMEDIATE")  # IMMEDIATE|GROUPED|MUTED
    popup_size = models.CharField(max_length=16, default="STANDARD")  # COMPACT|STANDARD|DETAILED
    popup_position = models.CharField(max_length=16, default="CENTER")
    theme_mode = models.CharField(max_length=16, default="FOLLOW_APP")  # FOLLOW_APP|LIGHT|DARK
    animation_enabled = models.BooleanField(default=True)
    reduced_motion = models.BooleanField(default=False)
    max_simultaneous = models.PositiveSmallIntegerField(default=3)
    auto_dismiss_ms = models.JSONField(default=default_auto_dismiss_ms, blank=True)
    quiet_hours_start = models.TimeField(null=True, blank=True)
    quiet_hours_end = models.TimeField(null=True, blank=True)
    timezone_name = models.CharField(max_length=64, default="Asia/Kathmandu")
    allow_critical_in_quiet = models.BooleanField(default=True)
    dnd_enabled = models.BooleanField(default=False)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "notif_preferences"
        unique_together = [("user", "category")]


class NotificationDelivery(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    event = models.ForeignKey(NotificationEvent, on_delete=models.CASCADE, related_name="deliveries")
    notification = models.ForeignKey(Notification, on_delete=models.CASCADE, null=True, blank=True, related_name="deliveries")
    recipient = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    delivery_channel = models.CharField(max_length=24, default="IN_APP")  # IN_APP|WEBSOCKET|POPUP
    delivery_status = models.CharField(max_length=24, default="DELIVERED")  # PENDING|DELIVERED|FAILED|SUPPRESSED_PREF
    attempt_count = models.PositiveSmallIntegerField(default=1)
    delivered_at = models.DateTimeField(null=True, blank=True)
    error_reference = models.CharField(max_length=255, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

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


class ConfirmationAudit(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, null=True, blank=True, related_name="confirmation_audits")
    actor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    action_type = models.CharField(max_length=64, db_index=True)
    source_object_type = models.CharField(max_length=64, blank=True)
    source_object_id = models.CharField(max_length=64, blank=True)
    source_reference = models.CharField(max_length=128, blank=True)
    confirmation_phrase_used = models.CharField(max_length=128, blank=True)
    second_approver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="second_approved_confirmations")
    confirmation_timestamp = models.DateTimeField(default=timezone.now)
    authorization_result = models.CharField(max_length=24, default="ALLOWED")  # ALLOWED|DENIED
    execution_result = models.CharField(max_length=24, default="SUCCESS")  # SUCCESS|FAILED|CANCELLED
    detail = models.TextField(blank=True)

    class Meta:
        db_table = "notif_confirmation_audits"
        ordering = ["-confirmation_timestamp"]


class NotificationGlobalConfiguration(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.OneToOneField("tenancy.Company", on_delete=models.CASCADE, related_name="notification_config")
    retention_days = models.PositiveIntegerField(default=180)
    critical_escalation_mandatory = models.BooleanField(default=True)
    mandatory_security_popup = models.BooleanField(default=True)
    rate_limit_per_minute = models.PositiveIntegerField(default=120)
    quiet_hours_enforced_for_non_critical = models.BooleanField(default=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "notif_global_configurations"
