from __future__ import annotations

from datetime import date, datetime

from sqlalchemy import Date, DateTime, Index, SmallInteger, String, Text, UniqueConstraint, func
from sqlalchemy.orm import Mapped, mapped_column

from app.db.base import Base


class PushSendLog(Base):
    """
    推送发送日志（用于幂等防重复 + 可观测）。
    """

    __tablename__ = "push_send_log"

    __table_args__ = (
        UniqueConstraint("client_user_id", "local_date", "slot_index", name="uniq_user_date_slot"),
        Index("idx_push_log_user_date", "client_user_id", "local_date"),
        Index("idx_push_log_status", "status"),
    )

    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True, comment="主键")

    client_user_id: Mapped[str] = mapped_column(String(length=64), nullable=False, comment="客户端用户标识（UUID）")
    local_date: Mapped[date] = mapped_column(Date, nullable=False, comment="用户时区的本地日期（用于幂等）")
    slot_index: Mapped[int] = mapped_column(SmallInteger, nullable=False, comment="当天第几条（1..times_per_day）")

    scheduled_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, comment="计划发送时间（UTC）")
    sent_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True, comment="实际发送时间（UTC）")

    status: Mapped[str] = mapped_column(String(length=16), nullable=False, server_default="scheduled", comment="scheduled/sent/failed")
    error: Mapped[str | None] = mapped_column(Text, nullable=True, comment="失败原因（可选）")

    created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.now(), comment="创建时间")

