from __future__ import annotations

from datetime import datetime

from pydantic import BaseModel, Field

from ...database.orm import CommissionRecordORM
from ...services.commission_service import CommissionPage
from .employee import EmployeeResponse


class CommissionRecordRequest(BaseModel):
    """提成记录维护请求。"""

    employee_id: int
    commission_month: str = Field(..., max_length=7)
    commission_type: str = Field(default="销售提成", max_length=64)
    amount: float = Field(default=0, ge=0)
    source_type: str = Field(default="manual", max_length=32)
    business_ref: str = Field(default="", max_length=128)
    remark: str = ""


class CommissionRecordResponse(BaseModel):
    """提成记录响应。"""

    id: int
    employee_id: int
    employee: EmployeeResponse
    commission_month: str
    commission_type: str
    amount: float
    source_type: str
    business_ref: str
    remark: str
    created_at: datetime
    updated_at: datetime

    @classmethod
    def from_orm_model(cls, record: CommissionRecordORM) -> "CommissionRecordResponse":
        return cls(
            id=record.id,
            employee_id=record.employee_id,
            employee=EmployeeResponse.from_orm_model(record.employee),
            commission_month=record.commission_month,
            commission_type=record.commission_type,
            amount=record.amount,
            source_type=record.source_type,
            business_ref=record.business_ref,
            remark=record.remark,
            created_at=record.created_at,
            updated_at=record.updated_at,
        )


class CommissionListResponse(BaseModel):
    """提成记录分页响应。"""

    items: list[CommissionRecordResponse]
    total: int
    page: int
    page_size: int

    @classmethod
    def from_page(cls, page: CommissionPage) -> "CommissionListResponse":
        return cls(
            items=[CommissionRecordResponse.from_orm_model(item) for item in page.items],
            total=page.total,
            page=page.page,
            page_size=page.page_size,
        )


class CommissionImportResponse(BaseModel):
    """提成 Excel 导入响应。"""

    imported_count: int
    message: str
