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


class ItemCategory(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="item_categories")
    parent = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="subcategories")
    code = models.CharField(max_length=24)
    name = models.CharField(max_length=120)
    is_active = models.BooleanField(default=True)

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

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


class UnitOfMeasure(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="units")
    code = models.CharField(max_length=16)
    name = models.CharField(max_length=64)

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

    def __str__(self) -> str:
        return self.code


class UnitConversion(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    from_unit = models.ForeignKey(UnitOfMeasure, on_delete=models.CASCADE, related_name="conversions_from")
    to_unit = models.ForeignKey(UnitOfMeasure, on_delete=models.CASCADE, related_name="conversions_to")
    factor = models.DecimalField(max_digits=14, decimal_places=6)

    class Meta:
        db_table = "unit_conversions"
        unique_together = [("company", "from_unit", "to_unit")]


class ItemMaster(models.Model):
    class ValuationMethod(models.TextChoices):
        FIFO = "FIFO", "First-In, First-Out (FIFO)"
        WEIGHTED_AVG = "WEIGHTED_AVG", "Weighted Average Cost"
        SPECIFIC_ID = "SPECIFIC_ID", "Specific Identification (Batch/Serial)"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="items")
    item_code = models.CharField(max_length=40)
    name = models.CharField(max_length=200)
    description = models.CharField(max_length=255, blank=True)
    category = models.ForeignKey(ItemCategory, on_delete=models.PROTECT, related_name="items")
    brand = models.CharField(max_length=80, blank=True)
    primary_unit = models.ForeignKey(UnitOfMeasure, on_delete=models.PROTECT, related_name="primary_items")
    purchase_unit = models.ForeignKey(
        UnitOfMeasure, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
    )
    issue_unit = models.ForeignKey(
        UnitOfMeasure, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
    )
    conversion_factor = models.DecimalField(max_digits=14, decimal_places=4, default=Decimal("1.0000"))
    min_stock = models.DecimalField(max_digits=14, decimal_places=3, default=Decimal("0.000"))
    max_stock = models.DecimalField(max_digits=14, decimal_places=3, default=Decimal("0.000"))
    reorder_level = models.DecimalField(max_digits=14, decimal_places=3, default=Decimal("0.000"))
    standard_rate = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    last_purchase_rate = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    valuation_method = models.CharField(
        max_length=16, choices=ValuationMethod.choices, default=ValuationMethod.WEIGHTED_AVG
    )
    tax_rate = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("13.00"))
    barcode_qr = models.CharField(max_length=80, blank=True)
    inventory_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="inventory_items"
    )
    expense_wip_account = models.ForeignKey(
        "accounting.Account", on_delete=models.PROTECT, null=True, blank=True, related_name="wip_items"
    )
    track_batch = models.BooleanField(default=False)
    track_serial = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)

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

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


class Warehouse(models.Model):
    class StoreKind(models.TextChoices):
        CENTRAL = "CENTRAL", "Central Warehouse"
        HEAD_OFFICE = "HEAD_OFFICE", "Head Office Store"
        BRANCH = "BRANCH", "Branch Warehouse"
        PROJECT = "PROJECT", "Project Warehouse"
        SITE_STORE = "SITE_STORE", "Construction Site Store"
        EQUIPMENT_YARD = "EQUIPMENT_YARD", "Equipment & Machinery Yard"
        TOOL_CUSTODY = "TOOL_CUSTODY", "Employee Tool Custody"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="warehouses")
    code = models.CharField(max_length=32)
    name = models.CharField(max_length=160)
    store_kind = models.CharField(max_length=20, choices=StoreKind.choices, default=StoreKind.SITE_STORE)
    branch = models.ForeignKey("tenancy.Branch", on_delete=models.PROTECT, null=True, blank=True)
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, null=True, blank=True)
    site = models.ForeignKey("projects.Site", on_delete=models.PROTECT, null=True, blank=True)
    custodian = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    allow_negative_stock = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)

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

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


class GoodsReceiptNote(models.Model):
    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        INSPECTED = "INSPECTED", "Quality Inspected"
        APPROVED = "APPROVED", "Approved & Stocked"
        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="grns")
    grn_number = models.CharField(max_length=40)
    grn_date = models.DateField(db_index=True)
    bs_date = models.CharField(max_length=16, blank=True)
    purchase_order = models.ForeignKey(
        "procurement.PurchaseOrder", on_delete=models.PROTECT, null=True, blank=True, related_name="grns"
    )
    vendor = models.ForeignKey("accounting.Party", on_delete=models.PROTECT, related_name="grns")
    warehouse = models.ForeignKey(Warehouse, on_delete=models.PROTECT, related_name="grns")
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, null=True, blank=True)
    site = models.ForeignKey("projects.Site", on_delete=models.PROTECT, null=True, blank=True)
    challan_no = models.CharField(max_length=64, blank=True)
    total_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    linked_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="grn_sources"
    )
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.DRAFT, db_index=True)
    remarks = models.TextField(blank=True)
    received_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="received_grns")
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="approved_grns"
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "grn_records"
        unique_together = [("company", "grn_number")]
        ordering = ["-grn_date", "-created_at"]

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


class GoodsReceiptLine(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    grn = models.ForeignKey(GoodsReceiptNote, on_delete=models.CASCADE, related_name="lines")
    po_line = models.ForeignKey(
        "procurement.PurchaseOrderLine", on_delete=models.PROTECT, null=True, blank=True, related_name="grn_lines"
    )
    item = models.ForeignKey(ItemMaster, on_delete=models.PROTECT)
    received_qty = models.DecimalField(max_digits=14, decimal_places=3)
    accepted_qty = models.DecimalField(max_digits=14, decimal_places=3)
    rejected_qty = models.DecimalField(max_digits=14, decimal_places=3, default=Decimal("0.000"))
    unit_rate = models.DecimalField(max_digits=14, decimal_places=2)
    amount = models.DecimalField(max_digits=18, decimal_places=2)
    batch_no = models.CharField(max_length=48, blank=True)
    serial_no = models.CharField(max_length=64, blank=True)
    expiry_date = models.DateField(null=True, blank=True)

    class Meta:
        db_table = "grn_lines"


class StockBatch(models.Model):
    """Per-receipt FIFO / Specific-ID cost layer."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    warehouse = models.ForeignKey(Warehouse, on_delete=models.PROTECT, related_name="batches")
    item = models.ForeignKey(ItemMaster, on_delete=models.PROTECT, related_name="batches")
    batch_no = models.CharField(max_length=48, blank=True, default="GENERAL")
    serial_no = models.CharField(max_length=64, blank=True)
    expiry_date = models.DateField(null=True, blank=True)
    received_date = models.DateField()
    received_qty = models.DecimalField(max_digits=16, decimal_places=3)
    remaining_qty = models.DecimalField(max_digits=16, decimal_places=3)
    unit_cost = models.DecimalField(max_digits=14, decimal_places=2)
    grn_line = models.ForeignKey(GoodsReceiptLine, on_delete=models.SET_NULL, null=True, blank=True)

    class Meta:
        db_table = "stock_batches"
        ordering = ["received_date", "id"]


class StockMovement(models.Model):
    """Append-only authoritative inventory & valuation movement ledger."""

    class MovementType(models.TextChoices):
        GRN_RECEIPT = "GRN_RECEIPT", "GRN Purchase Receipt"
        ISSUE = "ISSUE", "Material Issue to Project/Site"
        RETURN = "RETURN", "Material Return to Store"
        TRANSFER_OUT = "TRANSFER_OUT", "Inter-Store Transfer Out"
        TRANSFER_IN = "TRANSFER_IN", "Inter-Store Transfer In"
        ADJUSTMENT = "ADJUSTMENT", "Authorized Stock Adjustment"
        WRITE_OFF = "WRITE_OFF", "Damaged / Wastage Write-off"
        COUNT_VARIANCE = "COUNT_VARIANCE", "Physical Stock Reconciliation"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.PROTECT)
    warehouse = models.ForeignKey(Warehouse, on_delete=models.PROTECT, related_name="movements")
    item = models.ForeignKey(ItemMaster, on_delete=models.PROTECT, related_name="movements")
    batch = models.ForeignKey(StockBatch, on_delete=models.PROTECT, null=True, blank=True)
    movement_type = models.CharField(max_length=20, choices=MovementType.choices, db_index=True)
    movement_date = models.DateField(db_index=True)
    reference_no = models.CharField(max_length=48)
    quantity_delta = models.DecimalField(max_digits=16, decimal_places=3)
    unit_cost = models.DecimalField(max_digits=14, decimal_places=2)
    value_delta = models.DecimalField(max_digits=18, decimal_places=2)
    balance_qty_after = models.DecimalField(max_digits=16, decimal_places=3)
    balance_value_after = models.DecimalField(max_digits=18, decimal_places=2)
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT, null=True, blank=True)
    site = models.ForeignKey("projects.Site", on_delete=models.PROTECT, null=True, blank=True)
    cost_code = models.ForeignKey("projects.CostCode", on_delete=models.PROTECT, null=True, blank=True)
    boq_item = models.ForeignKey("accounting.BoqItem", on_delete=models.PROTECT, null=True, blank=True)
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.PROTECT, null=True, blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "stock_movements"
        ordering = ["movement_date", "created_at"]

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

    def delete(self, *args, **kwargs):
        raise PermissionError("StockMovement ledger rows cannot be deleted.")


class MaterialRequisition(models.Model):
    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        APPROVED = "APPROVED", "Approved for Issue"
        ISSUED = "ISSUED", "Issued"
        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="material_requisitions")
    requisition_no = models.CharField(max_length=40)
    requisition_date = models.DateField()
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT)
    site = models.ForeignKey("projects.Site", on_delete=models.PROTECT, null=True, blank=True)
    warehouse = models.ForeignKey(Warehouse, on_delete=models.PROTECT)
    requested_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    approved_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT, null=True, blank=True, related_name="+"
    )
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.DRAFT)
    remarks = models.CharField(max_length=255, blank=True)

    class Meta:
        db_table = "material_requisitions"
        unique_together = [("company", "requisition_no")]


class MaterialIssue(models.Model):
    class Status(models.TextChoices):
        DRAFT = "DRAFT", "Draft"
        APPROVED = "APPROVED", "Approved & Consumed"
        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="material_issues")
    issue_no = models.CharField(max_length=40)
    issue_date = models.DateField()
    bs_date = models.CharField(max_length=16, blank=True)
    requisition = models.ForeignKey(MaterialRequisition, on_delete=models.SET_NULL, null=True, blank=True)
    warehouse = models.ForeignKey(Warehouse, on_delete=models.PROTECT)
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT)
    site = models.ForeignKey("projects.Site", on_delete=models.PROTECT, null=True, blank=True)
    receiver_name = models.CharField(max_length=120, blank=True)
    total_cost = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    linked_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="issue_sources"
    )
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.DRAFT)
    issued_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "material_issues"
        unique_together = [("company", "issue_no")]
        ordering = ["-issue_date", "-created_at"]

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


class MaterialIssueLine(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    issue = models.ForeignKey(MaterialIssue, on_delete=models.CASCADE, related_name="lines")
    item = models.ForeignKey(ItemMaster, on_delete=models.PROTECT)
    batch = models.ForeignKey(StockBatch, on_delete=models.PROTECT, null=True, blank=True)
    quantity = models.DecimalField(max_digits=14, decimal_places=3)
    wastage_qty = models.DecimalField(max_digits=14, decimal_places=3, default=Decimal("0.000"))
    unit_cost = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    total_cost = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    cost_code = models.ForeignKey("projects.CostCode", on_delete=models.PROTECT, null=True, blank=True)
    boq_item = models.ForeignKey("accounting.BoqItem", on_delete=models.PROTECT, null=True, blank=True)

    class Meta:
        db_table = "material_issue_lines"


class MaterialReturn(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    return_no = models.CharField(max_length=40)
    return_date = models.DateField()
    warehouse = models.ForeignKey(Warehouse, on_delete=models.PROTECT)
    project = models.ForeignKey("projects.Project", on_delete=models.PROTECT)
    item = models.ForeignKey(ItemMaster, on_delete=models.PROTECT)
    quantity = models.DecimalField(max_digits=14, decimal_places=3)
    unit_cost = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    reason = models.CharField(max_length=255, blank=True)
    linked_voucher = models.ForeignKey("accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "material_returns"
        unique_together = [("company", "return_no")]


class StockTransfer(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    transfer_no = models.CharField(max_length=40)
    transfer_date = models.DateField()
    from_warehouse = models.ForeignKey(Warehouse, on_delete=models.PROTECT, related_name="outgoing_stock_transfers")
    to_warehouse = models.ForeignKey(Warehouse, on_delete=models.PROTECT, related_name="incoming_stock_transfers")
    item = models.ForeignKey(ItemMaster, on_delete=models.PROTECT)
    quantity = models.DecimalField(max_digits=14, decimal_places=3)
    status = models.CharField(max_length=16, default="COMPLETED")
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "stock_transfers"
        unique_together = [("company", "transfer_no")]


class StockCount(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE)
    count_no = models.CharField(max_length=40)
    count_date = models.DateField()
    warehouse = models.ForeignKey(Warehouse, on_delete=models.PROTECT)
    item = models.ForeignKey(ItemMaster, on_delete=models.PROTECT)
    book_qty = models.DecimalField(max_digits=16, decimal_places=3)
    physical_qty = models.DecimalField(max_digits=16, decimal_places=3)
    variance_qty = models.DecimalField(max_digits=16, decimal_places=3)
    remarks = models.CharField(max_length=255, blank=True)
    counted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "stock_counts"
        unique_together = [("company", "count_no")]

