from datetime import datetime

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

from app.core.card_key_types import CARD_TYPE_DURATION
from app.database import Base


class CardKey(Base):
    __tablename__ = "card_keys"

    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
    serial_number: Mapped[str] = mapped_column(String(64), unique=True, index=True)
    card_type: Mapped[str] = mapped_column(
        String(16), default=CARD_TYPE_DURATION, server_default=CARD_TYPE_DURATION
    )
    duration_days: Mapped[int] = mapped_column(Integer)
    points_amount: Mapped[float | None] = mapped_column(Float, nullable=True, default=None)
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )
    activated_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True, default=None
    )
    user_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True
    )
    username: Mapped[str | None] = mapped_column(String(64), nullable=True)
    oem_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True
    )
    agent_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True
    )
    remark: Mapped[str | None] = mapped_column(String(255), nullable=True)
    oem_remark: Mapped[str | None] = mapped_column(String(255), nullable=True)
    agent_remark: Mapped[str | None] = mapped_column(String(255), nullable=True)