from datetime import datetime

from sqlalchemy import (
    BigInteger,
    Boolean,
    DateTime,
    ForeignKey,
    Integer,
    String,
    Text,
    UniqueConstraint,
)
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.types import JSON

from app.models.base import BaseModel


class Announcement(BaseModel):
    """管理员发布的公告：全站或指定用户，单条存储。"""

    __tablename__ = "announcements"

    title: Mapped[str] = mapped_column(String(128), nullable=False)
    content: Mapped[str] = mapped_column(Text, nullable=False, comment="富文本 HTML")
    # announcement / promotion / system
    category: Mapped[str] = mapped_column(String(24), default="announcement", nullable=False)
    # all（全站） / specific（指定用户）
    target_type: Mapped[str] = mapped_column(String(16), default="all", nullable=False)
    target_user_ids: Mapped[list | None] = mapped_column(
        JSON, nullable=True, comment="target_type=specific 时的用户ID列表"
    )
    is_published: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False, index=True)
    published_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    created_by: Mapped[int | None] = mapped_column(BigInteger, nullable=True, comment="发布管理员ID")


class AnnouncementRead(BaseModel):
    """公告已读关联：记录某用户读过某公告。"""

    __tablename__ = "announcement_reads"
    __table_args__ = (
        UniqueConstraint("announcement_id", "user_id", name="uq_announcement_user"),
    )

    announcement_id: Mapped[int] = mapped_column(
        Integer, ForeignKey("announcements.id", ondelete="CASCADE"), nullable=False, index=True
    )
    user_id: Mapped[int] = mapped_column(BigInteger, nullable=False, index=True)
    read_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
