import uuid
from decimal import Decimal
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from .coa import Account, Department
from .parties import Party


class EmployeeProfile(models.Model):
    """Employee & site staff subledger linked to a Party (EMPLOYEE) for control-account reconciliation."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="employees")
    party = models.OneToOneField(Party, on_delete=models.PROTECT, related_name="employee_profile")
    employee_code = models.CharField(max_length=32)
    full_name = models.CharField(max_length=180)
    department = models.ForeignKey(
        Department, on_delete=models.SET_NULL, null=True, blank=True, related_name="employees"
    )
    designation = models.CharField(max_length=120, blank=True)
    project = models.ForeignKey(
        "projects.Project", on_delete=models.SET_NULL, null=True, blank=True, related_name="employees"
    )
    basic_salary = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    phone = models.CharField(max_length=40, blank=True)
    email = models.EmailField(blank=True)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "employee_ledgers"
        unique_together = [("company", "employee_code")]
        ordering = ["employee_code"]

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


class AdvanceRecord(models.Model):
    """Tracked advance master (Employee, Supplier, Customer, Mobilization, Site, Travel, Petty Cash)."""

    class AdvanceType(models.TextChoices):
        EMPLOYEE_ADVANCE = "EMPLOYEE_ADVANCE", "Employee Advance"
        SUPPLIER_ADVANCE = "SUPPLIER_ADVANCE", "Supplier Advance"
        CUSTOMER_ADVANCE = "CUSTOMER_ADVANCE", "Customer Advance"
        MOBILIZATION_ADVANCE = "MOBILIZATION_ADVANCE", "Contractor Mobilization Advance"
        SITE_ADVANCE = "SITE_ADVANCE", "Site Operational Advance"
        PROJECT_ADVANCE = "PROJECT_ADVANCE", "Project-Specific Advance"
        STAFF_LOAN = "STAFF_LOAN", "Staff Loan"
        TRAVEL_ADVANCE = "TRAVEL_ADVANCE", "Travel Advance"
        PETTY_CASH_ADVANCE = "PETTY_CASH_ADVANCE", "Petty Cash Advance"

    class Status(models.TextChoices):
        OPEN = "OPEN", "Open"
        PARTIALLY_ADJUSTED = "PARTIALLY_ADJUSTED", "Partially Adjusted"
        SETTLED = "SETTLED", "Settled"
        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="advance_records")
    advance_no = models.CharField(max_length=40)
    advance_type = models.CharField(max_length=28, choices=AdvanceType.choices, db_index=True)
    party = models.ForeignKey(Party, on_delete=models.PROTECT, related_name="advance_records")
    employee = models.ForeignKey(
        EmployeeProfile, on_delete=models.PROTECT, null=True, blank=True, related_name="advance_records"
    )
    project = models.ForeignKey(
        "projects.Project", on_delete=models.SET_NULL, null=True, blank=True, related_name="advance_records"
    )
    control_account = models.ForeignKey(Account, on_delete=models.PROTECT, related_name="advance_records")
    source_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="issued_advances"
    )
    issue_date = models.DateField()
    bs_date = models.CharField(max_length=16, blank=True)
    original_amount = models.DecimalField(max_digits=18, decimal_places=2)
    adjusted_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    status = models.CharField(max_length=24, choices=Status.choices, default=Status.OPEN, db_index=True)
    remarks = models.CharField(max_length=255, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "employee_advances"
        unique_together = [("company", "advance_no")]
        ordering = ["issue_date", "advance_no"]

    @property
    def remaining_amount(self) -> Decimal:
        rem = self.original_amount - self.adjusted_amount
        return rem if rem > Decimal("0.00") else Decimal("0.00")

    def clean(self):
        if self.original_amount <= 0:
            raise ValidationError("Original advance amount must exceed zero.")
        if self.adjusted_amount < 0 or self.adjusted_amount > self.original_amount:
            raise ValidationError("Adjusted advance cannot exceed original advance amount.")

    def __str__(self) -> str:
        return f"{self.advance_no} — {self.party.name} (Rem: {self.remaining_amount})"


class AdvanceAdjustment(models.Model):
    """Immutable adjustment / settlement log linked to original AdvanceRecord and settling Voucher."""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="advance_adjustments")
    advance = models.ForeignKey(AdvanceRecord, on_delete=models.PROTECT, related_name="adjustments")
    voucher = models.ForeignKey("accounting.Voucher", on_delete=models.PROTECT, related_name="advance_adjustments")
    adjusted_amount = models.DecimalField(max_digits=18, decimal_places=2)
    supporting_bill_ref = models.CharField(max_length=80, blank=True)
    notes = models.CharField(max_length=255, blank=True)
    adjusted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    adjusted_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "advance_adjustments"
        unique_together = [("advance", "voucher")]
        ordering = ["adjusted_at"]

    def __str__(self) -> str:
        return f"{self.advance.advance_no} -> {self.voucher.voucher_no} ({self.adjusted_amount})"


class PayrollLiability(models.Model):
    """Outstanding payroll / wages liability per employee tied to Wages Payable or Employee Payables."""

    class Status(models.TextChoices):
        UNPAID = "UNPAID", "Unpaid"
        PARTIALLY_PAID = "PARTIALLY_PAID", "Partially Paid"
        SETTLED = "SETTLED", "Settled"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="payroll_liabilities")
    payroll_ref = models.CharField(max_length=48)
    employee = models.ForeignKey(EmployeeProfile, on_delete=models.PROTECT, related_name="payroll_liabilities")
    project = models.ForeignKey("projects.Project", on_delete=models.SET_NULL, null=True, blank=True)
    period_label = models.CharField(max_length=40)
    control_account = models.ForeignKey(Account, on_delete=models.PROTECT, related_name="payroll_liabilities")
    source_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="payroll_liabilities"
    )
    gross_wages = models.DecimalField(max_digits=18, decimal_places=2)
    settled_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    status = models.CharField(max_length=20, choices=Status.choices, default=Status.UNPAID)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "payroll_liabilities"
        unique_together = [("company", "payroll_ref", "employee")]
        ordering = ["-created_at"]

    @property
    def outstanding_amount(self) -> Decimal:
        rem = self.gross_wages - self.settled_amount
        return rem if rem > Decimal("0.00") else Decimal("0.00")


class StaffLoan(models.Model):
    """Separate long-term employee loan schedule kept distinct from short-term advances."""

    class Status(models.TextChoices):
        ACTIVE = "ACTIVE", "Active"
        SETTLED = "SETTLED", "Settled"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    company = models.ForeignKey("tenancy.Company", on_delete=models.CASCADE, related_name="staff_loans")
    loan_no = models.CharField(max_length=40)
    employee = models.ForeignKey(EmployeeProfile, on_delete=models.PROTECT, related_name="staff_loans")
    control_account = models.ForeignKey(Account, on_delete=models.PROTECT, related_name="staff_loans")
    disbursement_voucher = models.ForeignKey(
        "accounting.Voucher", on_delete=models.SET_NULL, null=True, blank=True, related_name="staff_loans"
    )
    disbursement_date = models.DateField()
    principal_amount = models.DecimalField(max_digits=18, decimal_places=2)
    repaid_amount = models.DecimalField(max_digits=18, decimal_places=2, default=Decimal("0.00"))
    interest_rate_pct = models.DecimalField(max_digits=5, decimal_places=2, default=Decimal("0.00"))
    monthly_installment = models.DecimalField(max_digits=14, decimal_places=2, default=Decimal("0.00"))
    remaining_installments = models.PositiveSmallIntegerField(default=12)
    status = models.CharField(max_length=16, choices=Status.choices, default=Status.ACTIVE)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "staff_loans"
        unique_together = [("company", "loan_no")]
        ordering = ["disbursement_date"]

    @property
    def remaining_principal(self) -> Decimal:
        rem = self.principal_amount - self.repaid_amount
        return rem if rem > Decimal("0.00") else Decimal("0.00")

