import uuid
from decimal import Decimal
from django.conf import settings
from django.db import models
from apps.localization.bs_calendar import ad_to_bs


class OperationalDocument(models.Model):
    """Non-GL operational construction & store workflows (PR, PO, GRN, MB, Issue, Challan, Cert)."""

    class DocKind(models.TextChoices):
        PURCHASE_REQUISITION = "PURCHASE_REQUISITION", "Purchase Requisition (No GL)"
        PURCHASE_ORDER = "PURCHASE_ORDER", "Purchase Order (No GL)"
        GOODS_RECEIPT_NOTE = "GOODS_RECEIPT_NOTE", "Goods Receipt Note (GRN)"
        MATERIAL_ISSUE_NOTE = "MATERIAL_ISSUE_NOTE", "Material Issue Note (Perpetual WIP Trigger)"
        MATERIAL_RETURN_NOTE = "MATERIAL_RETURN_NOTE", "Material Return Note"
        SITE_MATERIAL_TRANSFER = "SITE_MATERIAL_TRANSFER", "Site Material Transfer"
        MEASUREMENT_BOOK = "MEASUREMENT_BOOK", "Measurement Book (MB)"
        WORK_ORDER = "WORK_ORDER", "Construction / Subcontract Work Order"
        JOB_COMPLETION_CERT = "JOB_COMPLETION_CERT", "Job Completion Certificate"
        DELIVERY_CHALLAN = "DELIVERY_CHALLAN", "Delivery Challan"
        SITE_INSPECTION_NOTE = "SITE_INSPECTION_NOTE", "Site Quality Inspection Note"
        PROJECT_PROGRESS_REPORT = "PROJECT_PROGRESS_REPORT", "Project Progress Report"
        SUBCONTRACTOR_CERTIFICATION = "SUBCONTRACTOR_CERTIFICATION", "Subcontractor Work Certification"

    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        SUBMITTED = "SUBMITTED", "Submitted"
        APPROVED = "APPROVED", "Approved"
        COMPLETED = "COMPLETED", "Completed"
        CANCELLED = "CANCELLED", "Cancelled"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey(
        "tenancy.Company", on_delete=models.CASCADE, related_name="operational_documents"
    )
    branch = models.ForeignKey(
        "tenancy.Branch", on_delete=models.PROTECT, null=True, blank=True
    )
    doc_kind = models.CharField(max_length=32, choices=DocKind.choices, db_index=True)
    doc_number = models.CharField(max_length=48)
    doc_date = models.DateField(db_index=True)
    bs_date = models.CharField(max_length=16, blank=True)
    project = models.ForeignKey(
        "projects.Project", on_delete=models.PROTECT, null=True, blank=True, related_name="operational_docs"
    )
    site = models.ForeignKey(
        "projects.Site", on_delete=models.PROTECT, null=True, blank=True
    )
    target_site = models.ForeignKey(
        "projects.Site", on_delete=models.PROTECT, null=True, blank=True, related_name="incoming_transfers"
    )
    party = models.ForeignKey(
        "accounting.Party", on_delete=models.PROTECT, null=True, blank=True, related_name="operational_docs"
    )
    reference_doc = models.ForeignKey(
        "self", on_delete=models.SET_NULL, null=True, blank=True, related_name="child_docs"
    )
    linked_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="operational_sources"
    )
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.DRAFT, db_index=True)
    total_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    remarks = models.TextField(blank=True)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="created_op_docs"
    )
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="approved_op_docs"
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "construction_operational_docs"
        unique_together = [("company", "doc_kind", "doc_number")]
        ordering = ["-doc_date", "-created_at"]

    def save(self, *args, **kwargs):
        if self.doc_date and not self.bs_date:
            self.bs_date = ad_to_bs(self.doc_date).isoformat()
        super().save(*args, **kwargs)


class OperationalDocumentLine(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    document = models.ForeignKey(OperationalDocument, on_delete=models.CASCADE, related_name="lines")
    line_no = models.PositiveSmallIntegerField(default=1)
    item_code = models.CharField(max_length=40, blank=True)
    item_name = models.CharField(max_length=200)
    unit = models.CharField(max_length=24, default="Units")
    quantity = models.DecimalField(max_digits=14, decimal_places=3, default=Decimal("0.000"))
    unit_rate = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    boq_item = models.ForeignKey(
        "accounting.BoqItem", on_delete=models.PROTECT, null=True, blank=True
    )
    cost_code = models.ForeignKey(
        "projects.CostCode", on_delete=models.PROTECT, null=True, blank=True
    )
    remarks = models.CharField(max_length=255, blank=True)

    class Meta:
        db_table = "construction_operational_lines"
        ordering = ["line_no"]


class InventoryStockBalance(models.Model):
    """Store quantity tracker separated from financial GL until authorized inventory issue/receipt event."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    site = models.ForeignKey("projects.Site", on_delete=models.PROTECT, null=True, blank=True)
    item_code = models.CharField(max_length=40)
    item_name = models.CharField(max_length=200)
    unit = models.CharField(max_length=24, default="Units")
    quantity_on_hand = models.DecimalField(max_digits=16, decimal_places=3, default=Decimal("0.000"))
    avg_unit_cost = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "construction_inventory_balances"
        unique_together = [("company", "site", "item_code")]
        ordering = ["item_code"]

