import json
from datetime import datetime
from typing import Literal

from pydantic import BaseModel, field_serializer, field_validator


class SecureChange(BaseModel):
    created_at: datetime
    type: Literal["login", "change_password", "change_email", "change_phone"]
    old: str | None
    new: str | None

    # 输入时：int -> datetime
    @field_validator("created_at", mode="before")
    @classmethod
    def from_timestamp(cls, v):  # type: ignore[no-untyped-def]  # noqa: ANN001, ANN206
        if isinstance(v, int):
            return datetime.fromtimestamp(v)
        return v

    # 输出时：datetime -> int
    @field_serializer("created_at")
    def to_timestamp(self, v: datetime) -> int:
        return int(v.timestamp())


def s_append_secure_changes(original_changes: str, new_change: SecureChange) -> str:
    changes: list[dict] = json.loads(original_changes)
    changes.append(new_change.model_dump())
    return json.dumps(changes)
