"""
審計日誌 Schemas
"""
from datetime import datetime
from typing import Optional, Dict, Any
from pydantic import Field, ConfigDict

from app.schemas.base import BaseSchema


class AuditLogBase(BaseSchema):
    """審計日誌基礎 Schema"""

    action: str = Field(..., max_length=50, description="操作類型 (create/update/delete/login)")
    resource_type: str = Field(..., max_length=50, description="資源類型 (employee/identity/department)")
    resource_id: Optional[int] = Field(None, description="資源 ID")
    performed_by: str = Field(..., max_length=100, description="操作者 SSO 帳號")
    details: Optional[Dict[str, Any]] = Field(None, description="詳細變更內容")
    ip_address: Optional[str] = Field(None, max_length=45, description="IP 位址")


class AuditLogCreate(AuditLogBase):
    """創建審計日誌 Schema"""

    model_config = ConfigDict(
        json_schema_extra={
            "example": {
                "action": "create",
                "resource_type": "employee",
                "resource_id": 1,
                "performed_by": "porsche.chen@lab.taipei",
                "details": {
                    "employee_id": "EMP001",
                    "legal_name": "陳保時",
                    "username_base": "porsche.chen"
                },
                "ip_address": "10.1.0.245"
            }
        }
    )


class AuditLogInDB(AuditLogBase):
    """資料庫中的審計日誌 Schema"""

    id: int
    performed_at: datetime

    model_config = ConfigDict(from_attributes=True)


class AuditLogResponse(AuditLogInDB):
    """審計日誌響應 Schema"""

    model_config = ConfigDict(
        json_schema_extra={
            "example": {
                "id": 1,
                "action": "create",
                "resource_type": "employee",
                "resource_id": 1,
                "performed_by": "porsche.chen@lab.taipei",
                "performed_at": "2020-01-01T12:00:00",
                "details": {
                    "employee_id": "EMP001",
                    "legal_name": "陳保時",
                    "username_base": "porsche.chen"
                },
                "ip_address": "10.1.0.245"
            }
        }
    )


class AuditLogListItem(BaseSchema):
    """審計日誌列表項 Schema"""

    id: int
    action: str
    resource_type: str
    resource_id: Optional[int] = None
    performed_by: str
    performed_at: datetime

    model_config = ConfigDict(from_attributes=True)


class AuditLogFilter(BaseSchema):
    """審計日誌篩選參數"""

    action: Optional[str] = None
    resource_type: Optional[str] = None
    resource_id: Optional[int] = None
    performed_by: Optional[str] = None
    start_date: Optional[datetime] = None
    end_date: Optional[datetime] = None

    model_config = ConfigDict(
        json_schema_extra={
            "example": {
                "action": "create",
                "resource_type": "employee",
                "start_date": "2020-01-01T00:00:00",
                "end_date": "2020-12-31T23:59:59"
            }
        }
    )
