from __future__ import annotations

from django.conf import settings
from django.db import models
from django.utils import timezone

from apps.core.ids import uuid7
from apps.core.models import UUIDModel


class ValidationRequest(UUIDModel):
    class Status(models.TextChoices):
        PENDING = "PENDING", "En attente"
        APPROVED = "APPROVED", "Approuvée"
        REJECTED = "REJECTED", "Rejetée"
        CANCELLED = "CANCELLED", "Annulée"
        CONFLICT = "CONFLICT", "Conflit"

    entity_type = models.CharField(max_length=80, db_index=True)
    entity_id = models.UUIDField(db_index=True)
    agency = models.ForeignKey("agencies.Agency", on_delete=models.CASCADE, related_name="validation_requests")
    requested_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="validation_requests")
    requested_at = models.DateTimeField(default=timezone.now)
    status = models.CharField(max_length=12, choices=Status.choices, default=Status.PENDING)
    amount_xaf = models.BigIntegerField(null=True, blank=True)
    comment = models.TextField(blank=True)
    origin_node = models.UUIDField(null=True, blank=True)
    version = models.PositiveIntegerField(default=1)

    class Meta:
        ordering = ["-requested_at"]
        verbose_name = "demande de validation"
        constraints = [
            models.UniqueConstraint(
                fields=["entity_type", "entity_id"],
                condition=models.Q(status="PENDING"),
                name="uniq_pending_validation_per_entity",
            )
        ]
        indexes = [models.Index(fields=["agency", "status", "requested_at"])]

    def __str__(self):
        return f"{self.entity_type} {self.entity_id} — {self.get_status_display()}"

    @property
    def is_pending(self):
        return self.status == self.Status.PENDING

    def required_approvals(self) -> int:
        from apps.finance.models import Threshold

        if self.amount_xaf is None:
            return 1
        threshold = Threshold.for_amount(self.agency_id, self.amount_xaf)
        return threshold.required_approvals if threshold else 1

    def allow_self_approval(self) -> bool:
        from apps.finance.models import Threshold

        if self.amount_xaf is None:
            return True
        threshold = Threshold.for_amount(self.agency_id, self.amount_xaf)
        return threshold.allow_self_approval if threshold else False


class ValidationDecision(UUIDModel):
    class Decision(models.TextChoices):
        APPROVE = "APPROVE", "Approbation"
        REJECT = "REJECT", "Rejet"

    request = models.ForeignKey(ValidationRequest, on_delete=models.CASCADE, related_name="decisions")
    validator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="validation_decisions")
    decision = models.CharField(max_length=8, choices=Decision.choices)
    comment = models.TextField(blank=True)
    decided_at = models.DateTimeField(default=timezone.now)
    source_node = models.UUIDField(null=True, blank=True)
    op_id = models.UUIDField(unique=True, default=uuid7)
    hash = models.CharField(max_length=64, blank=True)

    class Meta:
        ordering = ["decided_at"]
        verbose_name = "décision de validation"
        constraints = [
            models.UniqueConstraint(fields=["request", "validator"], name="uniq_decision_per_validator")
        ]

    def __str__(self):
        return f"{self.get_decision_display()} par {self.validator}"


class ValidationHistory(UUIDModel):
    request = models.ForeignKey(ValidationRequest, on_delete=models.CASCADE, related_name="history")
    from_status = models.CharField(max_length=12, blank=True)
    to_status = models.CharField(max_length=12)
    actor = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL, related_name="+")
    occurred_at = models.DateTimeField(default=timezone.now)
    comment = models.TextField(blank=True)

    class Meta:
        ordering = ["occurred_at"]
        verbose_name = "historique de validation"
