from __future__ import annotations

from datetime import datetime
from typing import Literal

from sqlalchemy import Boolean, DateTime, Enum, Index, String, UniqueConstraint, func
from sqlalchemy.orm import Mapped, mapped_column

from app.db.base import Base

PushEnv = Literal["dev", "prod"]
PushPlatform = Literal["ios", "android"]


class PushToken(Base):
    """
    Push Token 绑定表（Expo Push Token）。

    约束：
    - token 在同一 env + app_id 下必须唯一（避免重复推送）
    - 同一 client_user_id 可能会更新 token（重装/轮换/重新授权）
    """

    __tablename__ = "push_tokens"

    __table_args__ = (
        UniqueConstraint("env", "app_id", "push_token", name="uniq_env_app_token"),
        Index("idx_push_tokens_client_user_id", "client_user_id"),
        Index("idx_push_tokens_is_active", "is_active"),
    )

    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）")
    platform: Mapped[PushPlatform] = mapped_column(
        Enum("ios", "android", name="push_platform"),
        nullable=False,
        comment="平台",
    )

    push_token: Mapped[str] = mapped_column(String(length=255), nullable=False, comment="Expo Push Token")
    app_id: Mapped[str] = mapped_column(String(length=255), nullable=False, comment="bundle id / package name（用于隔离）")
    env: Mapped[PushEnv] = mapped_column(
        Enum("dev", "prod", name="push_env"),
        nullable=False,
        comment="环境隔离",
    )

    is_active: Mapped[bool] = mapped_column(
        Boolean,
        nullable=False,
        server_default="1",
        comment="是否有效（发送失败且不可恢复时置为 false）",
    )

    last_seen_at: Mapped[datetime] = mapped_column(
        DateTime,
        nullable=False,
        server_default=func.now(),
        server_onupdate=func.now(),
        comment="最后一次上报时间",
    )

