from __future__ import annotations

from pydantic import BaseModel, Field, field_validator

from app.enums.notification import NotificationType
from app.schemas.common import NaiveDatetime


class NotificationCreditsOut(BaseModel):
    """通知轮询接口携带的当前用户积分信息。"""

    balance: float = Field(..., description="当前用户最新积分余额")


class NotificationOut(BaseModel):
    id: str
    title: str
    content: str
    type: NotificationType
    is_read: bool
    created_at: NaiveDatetime

    @field_validator("type", mode="before")
    @classmethod
    def normalize_type(cls, value):
        """兼容历史数据或后台自定义通知类型，避免响应模型校验失败。"""
        if isinstance(value, NotificationType):
            return value
        if value is None:
            return NotificationType.UNKNOWN
        try:
            return NotificationType(str(value))
        except ValueError:
            return NotificationType.UNKNOWN

    model_config = {"from_attributes": True}


class NotificationListOut(BaseModel):
    items: list[NotificationOut]
    total: int
    credits: NotificationCreditsOut


class UnreadCountOut(BaseModel):
    count: int
