from django.db import models

from Company.models import company_details
from Employee.models import EmployeeDT


# ============================================================
# COMMON COMPANY-SCOPED MODEL
# ============================================================

class CompanyScopedModel(models.Model):

    # ---- audit fields (additive) ----
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    company = models.ForeignKey(
        company_details,
        on_delete=models.CASCADE,
        related_name="%(class)s_records",
    )

    created_at = models.DateTimeField(
        auto_now_add=True,
    )

    updated_at = models.DateTimeField(
        auto_now=True,
    )

    created_by = models.CharField(
        max_length=100,
        blank=True,
    )

    updated_by = models.CharField(
        max_length=100,
        blank=True,
    )

    class Meta:
        abstract = True


# ============================================================
# INSURANCE POLICY
# EXISTING / LEGACY MODEL
# ============================================================

class InsurancePolicy(CompanyScopedModel):

    POLICY_TYPES = [
        ("GMC", "Group Mediclaim"),
        ("GPA", "Group Personal Accident"),
        ("GTL", "Group Term Life"),
        ("TOP_UP", "Voluntary Super Top-Up"),
    ]

    STATUS_CHOICES = [
        ("Active", "Active"),
        ("Inactive", "Inactive"),
    ]

    policy_id = models.CharField(
        max_length=50,
    )

    name = models.CharField(
        max_length=200,
    )

    provider = models.CharField(
        max_length=200,
    )

    policy_number = models.CharField(
        max_length=100,
    )

    policy_type = models.CharField(
        max_length=20,
        choices=POLICY_TYPES,
    )

    sum_insured = models.DecimalField(
        max_digits=14,
        decimal_places=2,
    )

    coverage = models.CharField(
        max_length=500,
        blank=True,
    )

    eligible_dependents = models.CharField(
        max_length=300,
        blank=True,
    )

    co_pay_condition = models.CharField(
        max_length=300,
        blank=True,
    )

    room_rent_capping = models.CharField(
        max_length=300,
        blank=True,
    )

    maternity_cover = models.CharField(
        max_length=300,
        blank=True,
    )

    pre_post_hospitalization = models.CharField(
        max_length=300,
        blank=True,
    )

    tpa_name = models.CharField(
        max_length=200,
        blank=True,
    )

    tpa_helpline = models.CharField(
        max_length=30,
        blank=True,
    )

    start_date = models.DateField()

    renewal_date = models.DateField()

    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default="Active",
    )

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["company", "policy_id"],
                name="unique_insurance_policy_company_id",
            ),
            models.UniqueConstraint(
                fields=["company", "policy_number"],
                name="unique_insurance_policy_company_number",
            ),
        ]

    def __str__(self):
        return self.name


# ============================================================
# INSURANCE TPA
# EXISTING / LEGACY MODEL
# ============================================================

class InsuranceTPA(CompanyScopedModel):

    name = models.CharField(
        max_length=200,
    )

    corporate_account = models.CharField(
        max_length=200,
        blank=True,
    )

    phone = models.CharField(
        max_length=30,
        blank=True,
    )

    email = models.EmailField(
        blank=True,
    )

    preauth_tat_hours = models.PositiveIntegerField(
        default=2,
    )

    settlement_ratio = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        default=0,
    )

    is_active = models.BooleanField(
        default=True,
    )

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["company", "name"],
                name="unique_insurance_tpa_company_name",
            ),
        ]

    def __str__(self):
        return self.name


# ============================================================
# NETWORK HOSPITAL
# EXISTING / LEGACY MODEL
# ============================================================

class NetworkHospital(CompanyScopedModel):

    hospital_name = models.CharField(
        max_length=255,
    )

    address = models.CharField(
        max_length=500,
        blank=True,
        null=True,
    )

    city = models.CharField(
        max_length=100,
    )

    cashless_pre_auth = models.BooleanField(
        default=True,
    )

    direct_contact = models.CharField(
        max_length=30,
        blank=True,
        null=True,
    )

    is_active = models.BooleanField(
        default=True,
    )

    def __str__(self):
        return self.hospital_name


# ============================================================
# LEGACY INSURANCE DEPENDENT
#
# IMPORTANT:
# DO NOT ADD policy_id HERE.
#
# This model represents the EXISTING database table.
# ============================================================

class InsuranceDependent(CompanyScopedModel):

    dependent_id = models.CharField(
        max_length=50,
        unique=True
    )

    employee = models.ForeignKey(
        EmployeeDT,
        on_delete=models.CASCADE,
        related_name="legacy_insurance_dependents"
    )

    name = models.CharField(
        max_length=150
    )

    relation = models.CharField(
        max_length=50
    )

    gender = models.CharField(
        max_length=20
    )

    dob = models.DateField(
        null=True,
        blank=True
    )

    health_card_no = models.CharField(
        max_length=100,
        blank=True
    )

    endorsement_status = models.CharField(
        max_length=50,
        default="Active"
    )

    def __str__(self):
        return f"{self.dependent_id} - {self.name}"
# ============================================================
# LEGACY INSURANCE CLAIM
#
# IMPORTANT:
# This is kept because your existing API/backend data uses it.
# ============================================================

class InsuranceClaim(CompanyScopedModel):

    CLAIM_TYPE_CHOICES = [
        ("Cashless", "Cashless"),
        ("Reimbursement", "Reimbursement"),
    ]

    STATUS_CHOICES = [
        ("Pending", "Pending"),
        ("Approved", "Approved"),
        ("Rejected", "Rejected"),
        ("Settled", "Settled"),
    ]

    claim_id = models.CharField(
        max_length=100,
        unique=True,
    )

    employee = models.ForeignKey(
        EmployeeDT,
        on_delete=models.CASCADE,
        related_name="legacy_insurance_claims",
    )

    policy = models.ForeignKey(
        InsurancePolicy,
        on_delete=models.CASCADE,
        related_name="legacy_claims",
    )

    patient_name = models.CharField(
        max_length=200,
    )

    relation = models.CharField(
        max_length=50,
        blank=True,
        default="Self",
    )

    claim_type = models.CharField(
        max_length=30,
        choices=CLAIM_TYPE_CHOICES,
    )

    hospital_name = models.CharField(
        max_length=255,
    )

    city = models.CharField(
        max_length=100,
    )

    diagnosis = models.TextField(
        blank=True,
    )

    admission_date = models.DateField()

    discharge_date = models.DateField()

    claim_date = models.DateField()

    claimed_amount = models.DecimalField(
        max_digits=14,
        decimal_places=2,
        default=0,
    )

    approved_amount = models.DecimalField(
        max_digits=14,
        decimal_places=2,
        default=0,
    )

    status = models.CharField(
        max_length=30,
        choices=STATUS_CHOICES,
        default="Pending",
    )

    rejection_category = models.CharField(
        max_length=100,
        blank=True,
    )

    rejection_reason = models.TextField(
        blank=True,
    )

    tpa_ref = models.CharField(
        max_length=150,
        blank=True,
    )

    remarks = models.TextField(
        blank=True,
    )

    approved_at = models.DateTimeField(
        null=True,
        blank=True,
    )

    approved_by = models.CharField(
        max_length=150,
        blank=True,
    )

    rejected_at = models.DateTimeField(
        null=True,
        blank=True,
    )

    rejected_by = models.CharField(
        max_length=150,
        blank=True,
    )

    reopened_at = models.DateTimeField(
        null=True,
        blank=True,
    )

    reopened_by = models.CharField(
        max_length=150,
        blank=True,
    )

    settled_at = models.DateTimeField(
        null=True,
        blank=True,
    )

    settled_by = models.CharField(
        max_length=150,
        blank=True,
    )

    def __str__(self):
        return self.claim_id


# ============================================================
# LEGACY CLAIM DOCUMENT
# ============================================================

class ClaimDocument(models.Model):

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    DOCUMENT_TYPES = [
        ("Invoice", "Invoice"),
        ("Discharge Summary", "Discharge Summary"),
        ("Prescription", "Prescription"),
        ("Other", "Other"),
    ]

    claim = models.ForeignKey(
        InsuranceClaim,
        on_delete=models.CASCADE,
        related_name="documents",
    )

    document_type = models.CharField(
        max_length=50,
        choices=DOCUMENT_TYPES,
        default="Other",
    )

    file = models.FileField(
        upload_to="insurance/claims/%Y/%m/",
    )

    uploaded_at = models.DateTimeField(
        auto_now_add=True,
    )

    def __str__(self):
        return f"{self.claim.claim_id} - {self.document_type}"


# ============================================================
# NEW EMPLOYEE INSURANCE POLICY
#
# ADDITIVE MODEL
# Does NOT replace InsurancePolicy.
# ============================================================

class EmployeeInsurancePolicy(models.Model):

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    STATUS_CHOICES = [
        ("PENDING", "Pending"),
        ("ACTIVE", "Active"),
        ("EXPIRED", "Expired"),
        ("REJECTED", "Rejected"),
        ("CANCELLED", "Cancelled"),
    ]

    company = models.ForeignKey(
        company_details,
        on_delete=models.CASCADE,
        related_name="employee_insurance_policies",
    )

    employee = models.ForeignKey(
        EmployeeDT,
        on_delete=models.CASCADE,
        related_name="insurance_policies",
    )

    policy_number = models.CharField(
        max_length=100,
        unique=True,
    )

    insurer_name = models.CharField(
        max_length=255,
    )

    tpa_name = models.CharField(
        max_length=255,
        blank=True,
        null=True,
    )

    plan_name = models.CharField(
        max_length=255,
        blank=True,
        null=True,
    )

    policy_type = models.CharField(
        max_length=50,
        default="GROUP_HEALTH",
    )

    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default="PENDING",
        db_index=True,
    )

    sum_insured = models.DecimalField(
        max_digits=12,
        decimal_places=2,
        default=0,
    )

    employee_monthly_premium = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=0,
    )

    employer_monthly_premium = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=0,
    )

    start_date = models.DateField(
        blank=True,
        null=True,
    )

    end_date = models.DateField(
        blank=True,
        null=True,
    )

    e_card = models.FileField(
        upload_to="insurance/e_cards/",
        blank=True,
        null=True,
    )

    policy_document = models.FileField(
        upload_to="insurance/policies/",
        blank=True,
        null=True,
    )

    coverage_summary = models.TextField(
        blank=True,
        null=True,
    )

    exclusions = models.TextField(
        blank=True,
        null=True,
    )

    waiting_period = models.TextField(
        blank=True,
        null=True,
    )

    co_payment = models.CharField(
        max_length=100,
        blank=True,
        null=True,
    )

    created_at = models.DateTimeField(
        auto_now_add=True,
    )

    updated_at = models.DateTimeField(
        auto_now=True,
    )

    def save(self, *args, **kwargs):

        if self.employee_id:
            self.company_id = self.employee.company_id

        super().save(*args, **kwargs)

    def __str__(self):
        return (
            f"{self.employee.employee_code} - "
            f"{self.policy_number}"
        )


# ============================================================
# NEW EMPLOYEE INSURANCE DEPENDENT
#
# ADDITIVE MODEL.
#
# This is NOT InsuranceDependent.
# It has its own database table.
# ============================================================

class EmployeeInsuranceDependent(models.Model):

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )

    RELATIONSHIP_CHOICES = [
        ("SPOUSE", "Spouse"),
        ("CHILD", "Child"),
        ("FATHER", "Father"),
        ("MOTHER", "Mother"),
        ("OTHER", "Other"),
    ]

    employee = models.ForeignKey(
        EmployeeDT,
        on_delete=models.CASCADE,
        related_name="employee_insurance_dependents",
    )

    policy = models.ForeignKey(
        EmployeeInsurancePolicy,
        on_delete=models.CASCADE,
        related_name="employee_dependents",
    )

    name = models.CharField(
        max_length=150,
    )

    relationship = models.CharField(
        max_length=20,
        choices=RELATIONSHIP_CHOICES,
    )

    date_of_birth = models.DateField(
        blank=True,
        null=True,
    )

    gender = models.CharField(
        max_length=30,
        blank=True,
        null=True,
    )

    is_active = models.BooleanField(
        default=True,
    )

    created_at = models.DateTimeField(
        auto_now_add=True,
    )

    def save(self, *args, **kwargs):

        if self.policy_id:
            self.employee_id = self.policy.employee_id

        super().save(*args, **kwargs)

    def __str__(self):
        return (
            f"{self.name} - "
            f"{self.relationship}"
        )


# ============================================================
# NEW EMPLOYEE INSURANCE CLAIM
#
# ADDITIVE MODEL.
#
# Does NOT replace InsuranceClaim.
# ============================================================

class EmployeeInsuranceClaim(models.Model):

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    CLAIM_TYPE_CHOICES = [
        ("CASHLESS", "Cashless"),
        ("REIMBURSEMENT", "Reimbursement"),
    ]

    STATUS_CHOICES = [
        ("SUBMITTED", "Submitted"),
        ("UNDER_REVIEW", "Under Review"),
        ("PREAUTH_PENDING", "Pre-Authorization Pending"),
        ("PREAUTH_APPROVED", "Pre-Authorization Approved"),
        ("PREAUTH_REJECTED", "Pre-Authorization Rejected"),
        ("APPROVED", "Approved"),
        ("PARTIALLY_APPROVED", "Partially Approved"),
        ("REJECTED", "Rejected"),
        ("SETTLED", "Settled"),
        ("CANCELLED", "Cancelled"),
    ]

    company = models.ForeignKey(
        company_details,
        on_delete=models.CASCADE,
        related_name="employee_insurance_claims",
    )

    employee = models.ForeignKey(
        EmployeeDT,
        on_delete=models.CASCADE,
        related_name="employee_insurance_claims",
    )

    policy = models.ForeignKey(
        EmployeeInsurancePolicy,
        on_delete=models.CASCADE,
        related_name="claims",
    )

    claim_number = models.CharField(
        max_length=50,
        unique=True,
    )

    claim_type = models.CharField(
        max_length=20,
        choices=CLAIM_TYPE_CHOICES,
    )

    status = models.CharField(
        max_length=30,
        choices=STATUS_CHOICES,
        default="SUBMITTED",
        db_index=True,
    )

    hospital_name = models.CharField(
        max_length=255,
        blank=True,
        null=True,
    )

    hospital_city = models.CharField(
        max_length=100,
        blank=True,
        null=True,
    )

    admission_date = models.DateField(
        blank=True,
        null=True,
    )

    discharge_date = models.DateField(
        blank=True,
        null=True,
    )

    claimed_amount = models.DecimalField(
        max_digits=12,
        decimal_places=2,
        default=0,
    )

    approved_amount = models.DecimalField(
        max_digits=12,
        decimal_places=2,
        default=0,
    )

    employee_description = models.TextField(
        blank=True,
        null=True,
    )

    rejection_reason = models.TextField(
        blank=True,
        null=True,
    )

    insurer_reference = models.CharField(
        max_length=150,
        blank=True,
        null=True,
    )

    submitted_at = models.DateTimeField(
        auto_now_add=True,
    )

    decision_at = models.DateTimeField(
        blank=True,
        null=True,
    )

    decided_by = models.CharField(
        max_length=150,
        blank=True,
        null=True,
    )

    updated_at = models.DateTimeField(
        auto_now=True,
    )

    def save(self, *args, **kwargs):

        if self.employee_id:
            self.company_id = self.employee.company_id

        if not self.claim_number:
            import uuid

            self.claim_number = (
                "CLM-"
                + uuid.uuid4().hex[:10].upper()
            )

        super().save(*args, **kwargs)

    def __str__(self):
        return self.claim_number


# ============================================================
# NEW EMPLOYEE INSURANCE CLAIM DOCUMENT
# ============================================================

class InsuranceClaimDocument(models.Model):

    # ---- audit fields (additive) ----
    created_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who created this record (e.g. admin:<id> / employee:<id>)",
    )
    updated_by = models.CharField(
        max_length=150,
        null=True,
        blank=True,
        help_text="Who last updated this record (e.g. admin:<id> / employee:<id>)",
    )
    id_version = models.PositiveIntegerField(
        default=1,
        help_text="Record version counter",
    )
    is_active = models.BooleanField(
        default=True,
    )

    DOCUMENT_TYPES = [
        ("BILL", "Hospital Bill"),
        ("DISCHARGE", "Discharge Summary"),
        ("PRESCRIPTION", "Prescription"),
        ("REPORT", "Medical Report"),
        ("ID", "Identity Proof"),
        ("OTHER", "Other"),
    ]

    claim = models.ForeignKey(
        EmployeeInsuranceClaim,
        on_delete=models.CASCADE,
        related_name="claim_documents",
    )

    document_type = models.CharField(
        max_length=30,
        choices=DOCUMENT_TYPES,
    )

    document_name = models.CharField(
        max_length=255,
    )

    file = models.FileField(
        upload_to="insurance/claims/",
    )

    uploaded_at = models.DateTimeField(
        auto_now_add=True,
    )

    def __str__(self):
        return self.document_name


# ============================================================
# EMPLOYEE INSURANCE ENROLLMENT
# ADDITIVE MODEL
# ============================================================

class EmployeeInsuranceEnrollment(CompanyScopedModel):

    STATUS_CHOICES = [
        ("Pending", "Pending"),
        ("Active", "Active"),
        ("Rejected", "Rejected"),
        ("Inactive", "Inactive"),
    ]

    employee = models.ForeignKey(
        EmployeeDT,
        on_delete=models.CASCADE,
        related_name="insurance_enrollments",
    )

    policy = models.ForeignKey(
        InsurancePolicy,
        on_delete=models.PROTECT,
        related_name="employee_enrollments",
    )

    member_id = models.CharField(
        max_length=100,
        blank=True,
    )

    employee_monthly_premium = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=0,
    )

    employer_monthly_premium = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        default=0,
    )

    start_date = models.DateField(
        null=True,
        blank=True,
    )

    end_date = models.DateField(
        null=True,
        blank=True,
    )

    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default="Pending",
    )

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=[
                    "employee",
                    "policy",
                ],
                name="unique_employee_insurance_enrollment",
            )
        ]

    def save(self, *args, **kwargs):

        if self.employee_id:
            self.company_id = self.employee.company_id

        super().save(*args, **kwargs)

    def __str__(self):
        return (
            f"{self.employee.name} - "
            f"{self.policy.name}"
        )
        
        