from __future__ import annotations

from datetime import datetime

from pydantic import BaseModel

from ...database.orm import OperationLogORM
from ...services import OperationLogPage


class OperationLogDTO(BaseModel):
    """操作日志列表项。"""

    id: int
    user_id: int | None
    username: str
    role: str
    module: str
    action: str
    target_type: str
    target_id: str
    status: str
    detail: str
    ip_address: str
    user_agent: str
    created_at: datetime

    @classmethod
    def from_orm_model(cls, log: OperationLogORM) -> "OperationLogDTO":
        return cls(
            id=log.id,
            user_id=log.user_id,
            username=log.username,
            role=log.role,
            module=log.module,
            action=log.action,
            target_type=log.target_type,
            target_id=log.target_id,
            status=log.status,
            detail=log.detail,
            ip_address=log.ip_address,
            user_agent=log.user_agent,
            created_at=log.created_at,
        )


class OperationLogListResponse(BaseModel):
    """操作日志分页响应。"""

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

    @classmethod
    def from_page(cls, page: OperationLogPage) -> "OperationLogListResponse":
        return cls(
            items=[OperationLogDTO.from_orm_model(log) for log in page.items],
            total=page.total,
            page=page.page,
            page_size=page.page_size,
        )
