from sqlalchemy import String, Text, ForeignKey, Integer, Float, Date, Boolean, Index
from sqlalchemy.dialects.mysql import CHAR
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.core.models import BaseModel
from app.core.models.status import Status
from app.core.models.user import User
from app.modules.hris.models.master import SalaryComponent

class PayrollSnapshot(BaseModel):
    """
    Represents a finalized set of payslips for a specific period.
    
    A snapshot locks the calculated values for historical record keeping
    and ensures consistency even if master data (like salary) changes later.
    """
    __tablename__ = 'hris_payroll_snapshot'

    period_start: Mapped[Date] = mapped_column(Date, nullable=False)
    period_end: Mapped[Date] = mapped_column(Date, nullable=False)
    finalized_at: Mapped[Date | None] = mapped_column(Date, nullable=True)
    run_type: Mapped[str] = mapped_column(String(20), default='default', nullable=False) # default, on_demand
    requested_by_id: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('user.id'), nullable=True)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)

    status_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('status.id'), nullable=False) # e.g., 'payslip_draft', 'payslip_paid'

    # Relationships
    status = relationship('Status')
    requested_by = relationship('User', foreign_keys=[requested_by_id], viewonly=True)
    payslips = relationship('Payslip', back_populates='snapshot', cascade="all, delete-orphan")
    batches = relationship('PayrollBatch', back_populates='snapshot', cascade="all, delete-orphan")

    def __repr__(self):
        return f"<PayrollSnapshot {self.period_start} to {self.period_end}>"


class PayrollBatch(BaseModel):
    """
    Represents an execution batch for payroll processing.
    
    Used to track the progress and summary of a payroll run, 
    especially for on-demand requests involving multiple employees.
    """
    __tablename__ = 'hris_payroll_batch'

    snapshot_id: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('hris_payroll_snapshot.id'), nullable=True)
    requested_by_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('user.id'), nullable=False)
    run_type: Mapped[str] = mapped_column(String(20), default='on_demand', nullable=False)
    status: Mapped[str] = mapped_column(String(20), default='draft', nullable=False) # draft, processing, completed

    period_start: Mapped[Date] = mapped_column(Date, nullable=False)
    period_end: Mapped[Date] = mapped_column(Date, nullable=False)

    total_employees: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    generated_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    partial_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    skipped_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)

    notes: Mapped[str | None] = mapped_column(Text, nullable=True)

    # Relationships
    requested_by = relationship('User', foreign_keys=[requested_by_id], viewonly=True)
    snapshot = relationship('PayrollSnapshot', back_populates='batches')
    items = relationship('PayrollBatchItem', back_populates='batch', cascade="all, delete-orphan")
    payslips = relationship('Payslip', back_populates='source_batch')

    def __repr__(self):
        return f"<PayrollBatch {self.run_type} {self.period_start} to {self.period_end}>"


class PayrollBatchItem(BaseModel):
    """
    Represents an individual employee's processing result within a PayrollBatch.
    
    Stores the decision (e.g., generated, skipped) and references 
    to existing payslips if an overlap occurred.
    """
    __tablename__ = 'hris_payroll_batch_item'

    batch_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('hris_payroll_batch.id'), nullable=False)
    employee_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('core_employee.id'), nullable=False)

    requested_start: Mapped[Date] = mapped_column(Date, nullable=False)
    requested_end: Mapped[Date] = mapped_column(Date, nullable=False)

    covered_start: Mapped[Date | None] = mapped_column(Date, nullable=True)
    covered_end: Mapped[Date | None] = mapped_column(Date, nullable=True)

    decision: Mapped[str] = mapped_column(String(20), default='pending', nullable=False) # generated, partial, skipped
    reason: Mapped[str | None] = mapped_column(Text, nullable=True)
    existing_payslip_refs: Mapped[str | None] = mapped_column(Text, nullable=True) # CSV of Payslip IDs

    # Relationships
    batch = relationship('PayrollBatch', back_populates='items')
    employee = relationship('Employee', backref='payroll_batch_items')

    def __repr__(self):
        return f"<PayrollBatchItem {self.employee_id} {self.decision}>"


class Payslip(BaseModel):
    """
    Represents a calculated salary statement for an employee.
    
    Acts as a financial snapshot, storing all totals and metadata 
    at the time of generation. Linked to a parent PayrollSnapshot.
    """
    __tablename__ = 'hris_payslip'

    snapshot_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('hris_payroll_snapshot.id'), nullable=False)
    source_batch_id: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('hris_payroll_batch.id'), nullable=True)
    employee_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('core_employee.id'), nullable=False)

    period_start: Mapped[Date] = mapped_column(Date, nullable=False)
    period_end: Mapped[Date] = mapped_column(Date, nullable=False)
    covered_start_date: Mapped[Date] = mapped_column(Date, nullable=False)
    covered_end_date: Mapped[Date] = mapped_column(Date, nullable=False)
    run_type: Mapped[str] = mapped_column(String(20), default='default', nullable=False)

    # Financial Snapshots (Aggregated amounts)
    base_salary: Mapped[float] = mapped_column(Float, default=0.0)
    total_allowances: Mapped[float] = mapped_column(Float, default=0.0)
    total_deductions: Mapped[float] = mapped_column(Float, default=0.0)
    net_salary: Mapped[float] = mapped_column(Float, default=0.0)

    # Payment Info
    payment_method: Mapped[str | None] = mapped_column(String(50), nullable=True) # e.g., 'Bank Transfer', 'Cash'
    payment_account: Mapped[str | None] = mapped_column(String(255), nullable=True) # e.g., 'BCA - 123456789'
    paid_at: Mapped[Date | None] = mapped_column(Date, nullable=True)
    paid_by_id: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('user.id'), nullable=True)

    # Tax Specifics
    pph21_amount: Mapped[float] = mapped_column(Float, default=0.0)

    # Attendance Statistics (Captured at generation time)
    attendance_days: Mapped[int] = mapped_column(Integer, default=0)
    absence_days: Mapped[int] = mapped_column(Integer, default=0)
    overtime_hours: Mapped[float] = mapped_column(Float, default=0.0)
    late_minutes: Mapped[int] = mapped_column(Integer, default=0)

    status_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('status.id'), nullable=False) # payslip_draft, payslip_paid

    # Relationships
    snapshot = relationship('PayrollSnapshot', back_populates='payslips')
    source_batch = relationship('PayrollBatch', back_populates='payslips')
    employee = relationship('Employee', backref='payslips')
    status = relationship('Status')
    items = relationship('PayslipItem', back_populates='payslip', cascade="all, delete-orphan")
    paid_by_user = relationship("User", foreign_keys=[paid_by_id], viewonly=True)

    # Optimized index for coverage checks
    __table_args__ = (
        Index('ix_hris_payslip_employee_coverage', 'employee_id', 'covered_start_date', 'covered_end_date'),
    )

    def __repr__(self):
        return f"<Payslip {self.employee_id} {self.period_start}>"

class PayslipItem(BaseModel):
    """
    Represents an individual line item (earning or deduction) within a Payslip.
    
    Maintains a link to the master SalaryComponent for reference, but 
    stores a snapshot of the name and amount for audit integrity.
    """
    __tablename__ = 'hris_payslip_item'

    payslip_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('hris_payslip.id'), nullable=False)
    component_id: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('hris_salary_component.id'), nullable=True)

    name: Mapped[str] = mapped_column(String(100), nullable=False)
    type: Mapped[str] = mapped_column(String(20), nullable=False) # earning, deduction
    amount: Mapped[float] = mapped_column(Float, default=0.0)
    source_notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    
    # Logic flags
    is_system_generated: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    system_key: Mapped[str | None] = mapped_column(String(50), nullable=True) # e.g. 'unpaid_leave_deduction'
    is_override_locked: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    override_reason: Mapped[str | None] = mapped_column(Text, nullable=True)

    # Relationships
    payslip = relationship('Payslip', back_populates='items')

    def __repr__(self):
        return f"<PayslipItem {self.name} - {self.amount}>"

class Reimbursement(BaseModel):
    """
    Represents an employee expense claim for reimbursement.
    """
    __tablename__ = 'hris_reimbursement'

    employee_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('core_employee.id'), nullable=False)

    title: Mapped[str] = mapped_column(String(100), nullable=False)
    amount: Mapped[float] = mapped_column(Float, default=0.0)
    date: Mapped[Date] = mapped_column(Date, nullable=False)
    description: Mapped[str | None] = mapped_column(Text, nullable=True)
    file_path: Mapped[str | None] = mapped_column(String(255), nullable=True)

    status_id: Mapped[str] = mapped_column(CHAR(36), ForeignKey('status.id'), nullable=False)
    approved_by_id: Mapped[str | None] = mapped_column(CHAR(36), ForeignKey('user.id'), nullable=True)

    # Relationships
    employee = relationship('Employee', backref='reimbursements')
    status = relationship('Status')
    approved_by = relationship('User')

    def __repr__(self):
        return f"<Reimbursement {self.title} - {self.amount}>"
