from datetime import datetime

from pydantic import BaseModel, ConfigDict, Field, field_validator


class AdminUserOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: int
    username: str
    phone: str | None = None
    role_id: int
    oem_id: int | None = None
    agent_id: int | None = None
    vip_end_time: datetime | None = None
    device_serial: str = ""
    created_at: datetime
    updated_at: datetime


class AdminUserCreate(BaseModel):
    username: str = Field(min_length=1, max_length=64)
    password: str = Field(min_length=6, max_length=128)
    phone: str | None = Field(default=None, max_length=64)
    role_id: int = Field(default=0, ge=0, le=3)
    oem_id: int | None = None
    agent_id: int | None = None
    vip_end_time: datetime | None = None

    @field_validator("username")
    @classmethod
    def strip_username(cls, value: str) -> str:
        return value.strip()

    @field_validator("phone")
    @classmethod
    def normalize_phone(cls, value: str | None) -> str | None:
        if value is None:
            return None
        stripped = value.strip()
        return stripped or None


class AdminUserUpdate(BaseModel):
    username: str | None = Field(default=None, min_length=1, max_length=64)
    password: str | None = Field(default=None, min_length=6, max_length=128)
    phone: str | None = Field(default=None, max_length=64)
    role_id: int | None = Field(default=None, ge=0, le=3)
    oem_id: int | None = None
    agent_id: int | None = None
    vip_end_time: datetime | None = None
    clear_vip_end_time: bool = False

    @field_validator("username")
    @classmethod
    def strip_username(cls, value: str | None) -> str | None:
        if value is None:
            return None
        return value.strip()

    @field_validator("phone")
    @classmethod
    def normalize_phone(cls, value: str | None) -> str | None:
        if value is None:
            return None
        stripped = value.strip()
        return stripped or None
