# ============================================================
# ADDITIVE: Exit Management, Clearances & Full & Final (F&F) - models
# ------------------------------------------------------------
# DUPLICATE CHECK (all existing models were reviewed first):
#
#   People.ExitClearance      REUSED as the "exit case" (employee, resignation_date,
#                             last_working_day, reason, status and the department
#                             clearance checklist in `items`). NOT recreated.
#   People.AssetAllocation    REUSED - pending asset returns block IT/Admin clearance.
#   People.EmployeeLetter /
#   People.LetterTemplate     REUSED - relieving letter, experience certificate and
#                             the "Generated Letters Vault & Dispatch Log".
#   Employee.Payroll          REUSED (read only) - tells F&F whether the last month
#                             salary was already processed.
#   Employee.leave_models     REUSED (read only) - leave balances / encashable policy.
#   Employee.EmployeeDT       REUSED - Resignation_* / Last_Working_Day fields are
#                             kept in sync exactly like the existing exit/initiate.
#
# What did NOT exist and is added here (one row per exit case):
#   ExitResignationDetail   notice period, separation type, approval workflow
#                           (Submitted / Accepted / Rejected), handover.
#   ExitFnF                 Full & Final settlement statement + calculator result.
#   ExitInterview           exit interview feedback dossier.
#
# Screen tab                   -> data
# -----------------------------------------------------------
# Exit Dashboard               -> aggregates of the three below + ExitClearance
# Resignations & Notice        -> ExitClearance + ExitResignationDetail
# Departmental Clearances      -> ExitClearance.items (checklist JSON, extended with
#                                 status / remarks / approver_code keys)
# Full & Final (F&F)           -> ExitFnF
# Exit Interviews              -> ExitInterview
# Relieving & Experience       -> EmployeeLetter (existing)
#
# Imported at the bottom of People/models.py (one additive line).
# ============================================================

from decimal import Decimal

from django.db import models

from Company.models import company_details
from Employee.models import EmployeeDT

from .models import Audit, ExitClearance

__all__ = ["ExitResignationDetail", "ExitFnF", "ExitInterview"]


class ExitResignationDetail(Audit):
    """Notice / approval details of one ExitClearance (OneToOne)."""

    SEPARATION = [("Resignation", "Resignation"), ("Termination", "Termination"),
                  ("Retirement", "Retirement"), ("Contract End", "Contract End"),
                  ("Absconding", "Absconding")]
    APPROVAL = [("Submitted", "Submitted"), ("Accepted", "Accepted"), ("Rejected", "Rejected")]

    company = models.ForeignKey(company_details, on_delete=models.CASCADE,
                                related_name="people_exit_details")
    exit = models.OneToOneField(ExitClearance, on_delete=models.CASCADE, related_name="detail")

    separation_type = models.CharField(max_length=14, choices=SEPARATION, default="Resignation")
    notice_period_days = models.PositiveSmallIntegerField(default=30)
    notice_waived_days = models.PositiveSmallIntegerField(default=0)

    approval_status = models.CharField(max_length=10, choices=APPROVAL, default="Accepted", db_index=True)
    requested_by = models.CharField(max_length=10, default="HR")        # HR | Employee
    accepted_by = models.CharField(max_length=150, blank=True, null=True)
    accepted_on = models.DateField(null=True, blank=True)
    rejection_reason = models.TextField(blank=True, null=True)

    handover_to = models.ForeignKey(EmployeeDT, on_delete=models.SET_NULL, null=True, blank=True,
                                    related_name="exit_handovers")
    handover_notes = models.TextField(blank=True, null=True)
    hr_remarks = models.TextField(blank=True, null=True)

    class Meta:
        ordering = ["-id"]


class ExitFnF(Audit):
    """Full & Final settlement statement (OneToOne with ExitClearance)."""

    STATUS = [("Draft", "Draft"), ("Calculated", "Calculated"), ("Approved", "Approved"), ("Paid", "Paid")]
    Z = Decimal("0")

    company = models.ForeignKey(company_details, on_delete=models.CASCADE, related_name="people_exit_fnf")
    exit = models.OneToOneField(ExitClearance, on_delete=models.CASCADE, related_name="fnf")
    statement_no = models.CharField(max_length=40)                       # FNF-2026-0001
    status = models.CharField(max_length=10, choices=STATUS, default="Calculated", db_index=True)

    basic_monthly = models.DecimalField(max_digits=12, decimal_places=2, default=Z)
    per_day_rate = models.DecimalField(max_digits=12, decimal_places=2, default=Z)

    # ---- earnings ----
    pending_salary_days = models.DecimalField(max_digits=6, decimal_places=2, default=Z)
    pending_salary = models.DecimalField(max_digits=12, decimal_places=2, default=Z)
    leave_encashment_days = models.DecimalField(max_digits=6, decimal_places=2, default=Z)
    leave_encashment = models.DecimalField(max_digits=12, decimal_places=2, default=Z)
    gratuity = models.DecimalField(max_digits=12, decimal_places=2, default=Z)
    bonus = models.DecimalField(max_digits=12, decimal_places=2, default=Z)
    other_earnings = models.DecimalField(max_digits=12, decimal_places=2, default=Z)

    # ---- deductions ----
    notice_shortfall_days = models.DecimalField(max_digits=6, decimal_places=2, default=Z)
    notice_recovery = models.DecimalField(max_digits=12, decimal_places=2, default=Z)
    asset_recovery = models.DecimalField(max_digits=12, decimal_places=2, default=Z)
    advance_recovery = models.DecimalField(max_digits=12, decimal_places=2, default=Z)
    tds_deduction = models.DecimalField(max_digits=12, decimal_places=2, default=Z)
    other_deductions = models.DecimalField(max_digits=12, decimal_places=2, default=Z)

    # ---- totals ----
    gross_earnings = models.DecimalField(max_digits=13, decimal_places=2, default=Z)
    total_deductions = models.DecimalField(max_digits=13, decimal_places=2, default=Z)
    net_payable = models.DecimalField(max_digits=13, decimal_places=2, default=Z)

    components = models.JSONField(default=dict, blank=True)    # calculation breakdown / warnings
    remarks = models.TextField(blank=True, null=True)

    approved_by = models.CharField(max_length=150, blank=True, null=True)
    approved_on = models.DateTimeField(null=True, blank=True)
    paid_on = models.DateField(null=True, blank=True)
    payment_mode = models.CharField(max_length=30, blank=True, null=True)
    payment_reference = models.CharField(max_length=100, blank=True, null=True)

    class Meta:
        ordering = ["-id"]
        unique_together = (("company", "statement_no"),)


class ExitInterview(Audit):
    """Exit interview feedback dossier (OneToOne with ExitClearance)."""

    STATUS = [("Scheduled", "Scheduled"), ("Completed", "Completed"), ("Skipped", "Skipped")]
    MODE = [("In-person", "In-person"), ("Video", "Video"), ("Phone", "Phone"), ("Form", "Form")]
    REASONS = [("Better Opportunity", "Better Opportunity"), ("Compensation", "Compensation"),
               ("Career Growth", "Career Growth"), ("Relocation", "Relocation"),
               ("Higher Studies", "Higher Studies"), ("Work Environment", "Work Environment"),
               ("Personal / Family", "Personal / Family"), ("Health", "Health"), ("Other", "Other")]

    company = models.ForeignKey(company_details, on_delete=models.CASCADE,
                                related_name="people_exit_interviews")
    exit = models.OneToOneField(ExitClearance, on_delete=models.CASCADE, related_name="interview")

    status = models.CharField(max_length=10, choices=STATUS, default="Scheduled", db_index=True)
    mode = models.CharField(max_length=10, choices=MODE, default="In-person")
    scheduled_for = models.DateField(null=True, blank=True)
    conducted_on = models.DateField(null=True, blank=True)
    conducted_by = models.CharField(max_length=150, blank=True, null=True)

    overall_rating = models.DecimalField(max_digits=2, decimal_places=1, null=True, blank=True)   # 0 - 5
    reason_for_leaving = models.CharField(max_length=24, choices=REASONS, blank=True, null=True)
    feedback = models.TextField(blank=True, null=True)
    liked_most = models.TextField(blank=True, null=True)
    improvement_suggestions = models.TextField(blank=True, null=True)
    would_recommend = models.BooleanField(null=True, blank=True)
    would_rejoin = models.BooleanField(null=True, blank=True)
    submitted_by = models.CharField(max_length=10, default="HR")        # HR | Employee

    class Meta:
        ordering = ["-id"]
