from __future__ import annotations

from datetime import datetime

from pydantic import BaseModel

from ...database.orm import SalaryRecordORM
from ...services.report_service import PayrollReport


class DepartmentPayrollReportItem(BaseModel):
    department: str
    employee_count: int
    gross_salary: float
    net_salary: float


class SalaryRecordSummary(BaseModel):
    id: int
    employee_no: str
    employee_name: str
    department: str
    salary_month: str
    salary_mode: str
    base_pay: float
    commission_amount: float
    overtime_pay: float
    deduction_amount: float
    gross_salary: float
    net_salary: float
    created_at: datetime

    @classmethod
    def from_orm_model(cls, record: SalaryRecordORM) -> "SalaryRecordSummary":
        return cls(
            id=record.id,
            employee_no=record.employee_no,
            employee_name=record.employee_name,
            department=record.department,
            salary_month=record.salary_month,
            salary_mode=record.salary_mode,
            base_pay=record.base_pay,
            commission_amount=record.commission_amount,
            overtime_pay=record.overtime_pay,
            deduction_amount=record.deduction_amount,
            gross_salary=record.gross_salary,
            net_salary=record.net_salary,
            created_at=record.created_at,
        )


class PayrollReportResponse(BaseModel):
    salary_month: str | None
    totals: dict[str, float]
    attendance: dict[str, float]
    departments: list[DepartmentPayrollReportItem]
    recent_records: list[SalaryRecordSummary]

    @classmethod
    def from_report(cls, report: PayrollReport) -> "PayrollReportResponse":
        return cls(
            salary_month=report.salary_month,
            totals=report.totals,
            attendance=report.attendance,
            departments=[
                DepartmentPayrollReportItem(
                    department=str(item["department"]),
                    employee_count=int(item["employee_count"]),
                    gross_salary=float(item["gross_salary"]),
                    net_salary=float(item["net_salary"]),
                )
                for item in report.departments
            ],
            recent_records=[SalaryRecordSummary.from_orm_model(record) for record in report.recent_records],
        )
