from typing import Any

from pydantic import model_serializer
from sqlalchemy import Column, ForeignKey
from sqlmodel import Field, Relationship, SQLModel

from ..config import config_manager
from .model_story import Chatroom


class ModelUser(SQLModel, table=True):
    id: int = Field(default=None, primary_key=True)
    name: str
    display_name: str | None
    email: str | None
    phone: str | None
    avatar_url: str = Field(
        default=f"{config_manager.get('site_url', 'http://localhost:9000')}/nyahome/normal-avatar.png"
    )
    background_url: str = Field(
        default=f"{config_manager.get('site_url', 'http://localhost:9000')}/nyahome/normal-background.png"
    )
    description: str | None

    password: str
    is_admin: bool = Field(default=False)

    upload_files: list["ModelUploadFile"] = Relationship(back_populates="uploader")

    chatrooms: list[Chatroom] = Relationship(back_populates="creator")

    secure_changes: str = Field(default="[]")

    @model_serializer(mode="wrap")
    def serialize_user(self, handler) -> dict[str, Any]:  # type: ignore[no-untyped-def]  # noqa ANN001
        data = handler(self)
        data.pop("password", None)
        data.pop("secure_changes", None)
        return data  # type: ignore[no-any-return]


class ModelUploadFile(SQLModel, table=True):
    id: int = Field(default=None, primary_key=True)
    original_name: str
    safe_name: str
    download_url: str

    uploader_id: int = Field(sa_column=Column(ForeignKey("modeluser.id", name="fk_chatroom_creator")))
    uploader: ModelUser = Relationship(back_populates="upload_files")
