"""一次性任务完成记录表。

像"打开消息提醒"这类只能领一次的任务,完成后写一行,(user_id, task_key) 唯一,
防止重复领奖。可循环领取的任务(签到)不走这张表,各有专表。
"""
from __future__ import annotations

from datetime import datetime

from sqlalchemy import DateTime, ForeignKey, Integer, String, UniqueConstraint, func
from sqlalchemy.orm import Mapped, mapped_column

from app.db.base import Base


class UserTask(Base):
    __tablename__ = "user_task"
    __table_args__ = (
        UniqueConstraint("user_id", "task_key", name="uq_task_user_key"),
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    user_id: Mapped[int] = mapped_column(
        Integer, ForeignKey("user.id"), index=True, nullable=False
    )
    # 任务标识,见 app.core.rewards.TASK_REWARDS
    task_key: Mapped[str] = mapped_column(String(48), nullable=False)
    status: Mapped[str] = mapped_column(String(16), nullable=False, default="completed")
    coin_awarded: Mapped[int] = mapped_column(Integer, nullable=False, default=0)

    completed_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), nullable=False
    )

    def __repr__(self) -> str:  # pragma: no cover
        return f"<UserTask user_id={self.user_id} key={self.task_key}>"
