import uuid
from decimal import Decimal
from django.db import models
from apps.localization.tax import validate_nepal_pan
from .coa import Account


class Party(models.Model):
    """Customer, Supplier, Subcontractor & Employee subledger master tied to Control Accounts."""

    class PartyType(models.TextChoices):
        CUSTOMER = "CUSTOMER", "Customer / Client (Debtor)"
        SUPPLIER = "SUPPLIER", "Supplier / Vendor (Creditor)"
        SUBCONTRACTOR = "SUBCONTRACTOR", "Subcontractor / Contractor"
        EMPLOYEE = "EMPLOYEE", "Employee / Site Staff"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="parties")
    party_type = models.CharField(max_length=20, choices=PartyType.choices, db_index=True)
    code = models.CharField(max_length=32)
    name = models.CharField(max_length=200)
    pan_vat_no = models.CharField(max_length=20, blank=True)
    address = models.CharField(max_length=255, blank=True)
    phone = models.CharField(max_length=40, blank=True)
    email = models.EmailField(blank=True)
    credit_limit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    payment_terms_days = models.PositiveSmallIntegerField(default=30)
    default_tds_category = models.CharField(max_length=40, blank=True)
    control_account = models.ForeignKey(
        Account, on_delete=models.PROTECT, null=True, blank=True, related_name="parties"
    )
    project = models.ForeignKey(
        "projects.Project", on_delete=models.PROTECT, null=True, blank=True, related_name="parties"
    )
    opening_debit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    opening_credit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "parties"
        unique_together = [("company", "code")]
        ordering = ["name"]

    def clean(self):
        from django.core.exceptions import ValidationError

        if self.pan_vat_no and not validate_nepal_pan(self.pan_vat_no):
            raise ValidationError({"pan_vat_no": "Nepal PAN/VAT must be 9 digits."})

    def __str__(self) -> str:
        return f"{self.code} — {self.name} ({self.party_type})"


class PartyLedgerEntry(models.Model):
    """Append-only party subledger entries written atomically alongside LedgerEntry."""

    class EntryKind(models.TextChoices):
        INVOICE = "INVOICE", "Invoice / Bill"
        PAYMENT = "PAYMENT", "Supplier / Contractor Payment"
        RECEIPT = "RECEIPT", "Customer Receipt"
        ADVANCE = "ADVANCE", "Mobilization / Advance"
        RETENTION = "RETENTION", "Retention Hold / Release"
        TDS = "TDS", "Withholding TDS"
        RETURN = "RETURN", "Debit / Credit Note Return"
        ADJUSTMENT = "ADJUSTMENT", "Authorized Adjustment"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.PROTECT)
    party = models.ForeignKey(Party, on_delete=models.PROTECT, related_name="ledger_entries")
    control_account = models.ForeignKey(Account, on_delete=models.PROTECT)
    voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.PROTECT, related_name="party_ledger_entries"
    )
    project = models.ForeignKey(
        "projects.Project", on_delete=models.PROTECT, null=True, blank=True
    )
    entry_date = models.DateField(db_index=True)
    bs_date = models.CharField(max_length=16, blank=True)
    due_date = models.DateField(null=True, blank=True)
    entry_kind = models.CharField(max_length=16, choices=EntryKind.choices, default=EntryKind.INVOICE)
    reference_no = models.CharField(max_length=64, blank=True)
    debit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    credit = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    retention_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    advance_adjusted = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    narration = models.CharField(max_length=255, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "party_ledgers"
        ordering = ["entry_date", "created_at"]

    def save(self, *args, **kwargs):
        if not self._state.adding:
            raise PermissionError("PartyLedgerEntry records are immutable.")
        super().save(*args, **kwargs)

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


class BillAllocation(models.Model):
    """Invoice-wise settlement / partial payment & advance adjustment against specific bills."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    party = models.ForeignKey(Party, on_delete=models.PROTECT, related_name="bill_allocations")
    settlement_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.CASCADE, related_name="settlement_allocations"
    )
    against_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.PROTECT, related_name="settled_by_allocations"
    )
    allocated_amount = models.DecimalField(max_digits=18, decimal_places=2)
    discount_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    tds_withheld = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    retention_released = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    allocated_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "bill_allocations"
        unique_together = [("settlement_voucher", "against_voucher")]

