# ============================================================
# ADDITIVE: Leave Management & WFH Engine - models
# ------------------------------------------------------------
# The existing Employee.models.LeaveRequest is NOT touched.
# These models sit next to it and add everything the
# "Leave Management & Work From Home (WFH) Engine" screens need:
#
#   LeavePolicy            -> Leave Policies tab   (PL / CL / SL / Unpaid)
#   LeaveBalance           -> Leave Balances tab   (per employee, per FY)
#   WFHPolicy              -> WFH & Remote Policies tab (one per company)
#   WFHRequest             -> WFH requests + weekly quota + notice window
#   ApprovalWorkflowStep   -> Approval Workflow tab (configurable chain)
#   ApprovalAction         -> one row per tier per request (the pipeline)
#   ReportingHierarchy     -> who is the manager / HOD of an employee
#
# This module is imported at the very bottom of Employee/models.py
# (one additive line) so Django registers the models in the
# "Employee" app.
# ============================================================

from datetime import time
from decimal import Decimal

from django.db import models

from Company.models import company_details


__all__ = [
    "LeavePolicy", "LeaveBalance", "WFHPolicy", "WFHRequest",
    "ApprovalWorkflowStep", "ApprovalAction", "ReportingHierarchy",
]


LEAVE_TYPE_CHOICES = [
    ("Paid Leave", "Paid Leave"),          # Privilege / Earned Leave (PL)
    ("Sick Leave", "Sick Leave"),          # SL
    ("Casual Leave", "Casual Leave"),      # CL
    ("Unpaid Leave", "Unpaid Leave"),
]

REQUEST_TYPE_CHOICES = [
    ("leave", "Leave"),
    ("wfh", "Work From Home"),
]

APPROVER_TYPE_CHOICES = [
    ("reporting_manager", "Reporting Manager"),
    ("hod", "Department HOD"),
    ("hr", "HR Compliance & Payroll"),
]


class _AuditMixin(models.Model):
    """Same audit convention as the rest of the project."""

    # ---- audit fields (additive) ----
    is_active = models.BooleanField(
        default=True,
    )

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    created_by = models.CharField(max_length=150, null=True, blank=True)
    updated_by = models.CharField(max_length=150, null=True, blank=True)

    id_version = models.PositiveIntegerField(default=1)

    class Meta:
        abstract = True


# ============================================================
# LEAVE POLICY  (Leave Policies tab)
# ============================================================

class LeavePolicy(_AuditMixin):

    company = models.ForeignKey(
        company_details, on_delete=models.CASCADE,
        related_name="leave_policies",
    )

    leave_type = models.CharField(max_length=20, choices=LEAVE_TYPE_CHOICES)

    code = models.CharField(
        max_length=10, blank=True, default="",
        help_text="Short code shown in the UI, e.g. PL / CL / SL",
    )

    title = models.CharField(max_length=150, blank=True, default="")

    description = models.TextField(blank=True, default="")

    annual_quota = models.DecimalField(
        max_digits=6, decimal_places=1, null=True, blank=True,
        help_text="Days per financial year. Empty = unlimited (e.g. unpaid)",
    )

    accrual_per_month = models.DecimalField(
        max_digits=4, decimal_places=2, null=True, blank=True,
        help_text="Credited per completed month of service (e.g. 1.5 for PL)",
    )

    carry_forward = models.BooleanField(default=False)

    max_carry_forward_days = models.DecimalField(
        max_digits=6, decimal_places=1, default=Decimal("0"),
    )

    encashable = models.BooleanField(default=False)

    max_encashable_days = models.DecimalField(
        max_digits=6, decimal_places=1, default=Decimal("0"),
        help_text="Maximum days encashable upon separation",
    )

    medical_certificate_after_days = models.PositiveIntegerField(
        null=True, blank=True,
        help_text="Medical certificate mandatory for absences longer than N consecutive working days",
    )

    min_notice_hours = models.PositiveIntegerField(default=0)

    is_paid = models.BooleanField(default=True)

    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ["id"]
        constraints = [
            models.UniqueConstraint(
                fields=["company", "leave_type"],
                name="unique_company_leave_policy_type",
            )
        ]

    def __str__(self):
        return f"{self.company_id} - {self.leave_type} ({self.annual_quota})"


# ============================================================
# LEAVE BALANCE  (Leave Balances tab)
# ------------------------------------------------------------
# A row is an OVERRIDE of the policy default for one employee,
# one leave type, one financial year. "Used" is never stored -
# it is computed live from approved LeaveRequest rows.
# ============================================================

class LeaveBalance(_AuditMixin):

    company = models.ForeignKey(
        company_details, on_delete=models.CASCADE,
        related_name="leave_balances",
    )

    Employee_ID = models.CharField(max_length=100, db_index=True)

    leave_type = models.CharField(max_length=20, choices=LEAVE_TYPE_CHOICES)

    financial_year = models.CharField(
        max_length=7, help_text="e.g. 2026-27 (April - March)",
    )

    allocated = models.DecimalField(
        max_digits=6, decimal_places=1, default=Decimal("0"),
    )

    carried_forward = models.DecimalField(
        max_digits=6, decimal_places=1, default=Decimal("0"),
    )

    adjustment = models.DecimalField(
        max_digits=6, decimal_places=1, default=Decimal("0"),
        help_text="Manual +/- correction by HR",
    )

    remarks = models.TextField(blank=True, null=True)

    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ["Employee_ID", "leave_type"]
        constraints = [
            models.UniqueConstraint(
                fields=["company", "Employee_ID", "leave_type", "financial_year"],
                name="unique_leave_balance_row",
            )
        ]
        indexes = [models.Index(fields=["company", "financial_year"])]

    def __str__(self):
        return f"{self.Employee_ID} {self.leave_type} {self.financial_year}"


# ============================================================
# WFH POLICY  (WFH & Remote Policies tab) - one row per company
# ============================================================

class WFHPolicy(_AuditMixin):

    company = models.OneToOneField(
        company_details, on_delete=models.CASCADE,
        related_name="wfh_policy",
    )

    is_enabled = models.BooleanField(default=True)

    weekly_quota_days = models.PositiveIntegerField(
        default=2, help_text="Max WFH days per week per employee",
    )

    advance_notice_hours = models.PositiveIntegerField(
        default=24, help_text="WFH must be applied at least this many hours ahead",
    )

    work_start_time = models.TimeField(
        default=time(9, 0),
        help_text="Notice is measured up to this time on the WFH date",
    )

    description = models.TextField(blank=True, default="")

    def __str__(self):
        return f"WFH policy company={self.company_id}"


# ============================================================
# WFH REQUEST
# ============================================================

class WFHRequest(_AuditMixin):

    STATUS_CHOICES = [
        ("Pending", "Pending"),
        ("Approved", "Approved"),
        ("Rejected", "Rejected"),
        ("Cancelled", "Cancelled"),
    ]

    company = models.ForeignKey(
        company_details, on_delete=models.CASCADE,
        related_name="wfh_requests",
    )

    Employee_ID = models.CharField(max_length=100, db_index=True)

    Name = models.CharField(max_length=100, blank=True, null=True)

    wfh_date = models.DateField()

    reason = models.TextField(blank=True, null=True)

    status = models.CharField(
        max_length=10, choices=STATUS_CHOICES, default="Pending", db_index=True,
    )

    notice_hours = models.DecimalField(
        max_digits=8, decimal_places=1, default=Decimal("0"),
        help_text="Advance notice given when the request was submitted",
    )

    reviewed_by = models.CharField(max_length=150, blank=True, null=True)
    reviewed_at = models.DateTimeField(blank=True, null=True)
    review_comment = models.TextField(blank=True, null=True)

    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ["-created_at", "-id"]
        indexes = [
            models.Index(fields=["company", "status"]),
            models.Index(fields=["company", "wfh_date"]),
        ]

    def __str__(self):
        return f"{self.Employee_ID} WFH {self.wfh_date} ({self.status})"


# ============================================================
# APPROVAL WORKFLOW (Approval Workflow tab)
# ------------------------------------------------------------
# Configurable approver chain per request type. When a company
# has no rows, the built-in default chain is used
# (Manager 12h -> HOD 12h -> HR 24h).
# ============================================================

class ApprovalWorkflowStep(_AuditMixin):

    company = models.ForeignKey(
        company_details, on_delete=models.CASCADE,
        related_name="leave_workflow_steps",
    )

    request_type = models.CharField(max_length=10, choices=REQUEST_TYPE_CHOICES)

    step_order = models.PositiveIntegerField()

    name = models.CharField(max_length=100)

    approver_type = models.CharField(max_length=20, choices=APPROVER_TYPE_CHOICES)

    sla_hours = models.PositiveIntegerField(default=12)

    description = models.CharField(max_length=200, blank=True, default="")

    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ["request_type", "step_order"]
        constraints = [
            models.UniqueConstraint(
                fields=["company", "request_type", "step_order"],
                name="unique_company_workflow_step_order",
            )
        ]

    def __str__(self):
        return f"{self.request_type} #{self.step_order} {self.name}"


class ApprovalAction(_AuditMixin):
    """One row per approval tier of one request (the live pipeline)."""

    STATUS_CHOICES = [
        ("Pending", "Pending"),
        ("Approved", "Approved"),
        ("Rejected", "Rejected"),
        ("Skipped", "Skipped"),
    ]

    company = models.ForeignKey(
        company_details, on_delete=models.CASCADE,
        related_name="leave_approval_actions",
    )

    request_type = models.CharField(max_length=10, choices=REQUEST_TYPE_CHOICES)

    request_id = models.PositiveIntegerField(db_index=True)

    step_order = models.PositiveIntegerField()

    step_name = models.CharField(max_length=100)

    approver_type = models.CharField(max_length=20, choices=APPROVER_TYPE_CHOICES)

    approver_code = models.CharField(
        max_length=100, blank=True, null=True,
        help_text="Employee code of the designated approver (manager / HOD)",
    )

    sla_hours = models.PositiveIntegerField(default=12)

    due_at = models.DateTimeField(blank=True, null=True)

    status = models.CharField(
        max_length=10, choices=STATUS_CHOICES, default="Pending", db_index=True,
    )

    acted_by = models.CharField(max_length=150, blank=True, null=True)
    acted_at = models.DateTimeField(blank=True, null=True)
    comment = models.TextField(blank=True, null=True)

    class Meta:
        ordering = ["request_type", "request_id", "step_order"]
        indexes = [
            models.Index(fields=["company", "request_type", "request_id"]),
            models.Index(fields=["company", "status", "approver_code"]),
        ]

    def __str__(self):
        return f"{self.request_type}:{self.request_id} step {self.step_order} ({self.status})"


# ============================================================
# REPORTING HIERARCHY (who approves whom)
# ============================================================

class ReportingHierarchy(_AuditMixin):

    company = models.ForeignKey(
        company_details, on_delete=models.CASCADE,
        related_name="reporting_hierarchy",
    )

    Employee_ID = models.CharField(max_length=100, db_index=True)

    manager_code = models.CharField(max_length=100, blank=True, null=True)

    hod_code = models.CharField(max_length=100, blank=True, null=True)

    is_active = models.BooleanField(default=True)

    class Meta:
        ordering = ["Employee_ID"]
        constraints = [
            models.UniqueConstraint(
                fields=["company", "Employee_ID"],
                name="unique_company_reporting_hierarchy",
            )
        ]

    def __str__(self):
        return f"{self.Employee_ID} -> mgr {self.manager_code} / hod {self.hod_code}"
