import uuid
from datetime import datetime

from sqlalchemy import DateTime, ForeignKey, String, Uuid, func
from sqlalchemy.orm import Mapped, mapped_column

from app.db.session import Base


class DeviceToken(Base):
    """An FCM registration token for one installed app instance, tied
    to whichever user was logged in when it was registered (see
    app.api.v1.endpoints.notifications.register_device_token). A user
    can have several — one per device they're logged into — so
    app.services.push.notify_user pushes to all of them rather than
    just the most recent.

    token is globally unique rather than unique-per-user: the same
    physical install can only ever be logged into one account at a
    time, so a re-registration (app restart, token refresh, or a
    different account logging in on the same device) upserts the
    existing row's user_id/platform rather than creating a duplicate.
    A token FCM reports as unregistered/invalid is deleted outright by
    app.services.push rather than just marked inactive — there's
    nothing useful left to keep once FCM will no longer deliver to
    it."""

    __tablename__ = "device_tokens"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    user_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True
    )
    token: Mapped[str] = mapped_column(String(255), unique=True, nullable=False)
    platform: Mapped[str | None] = mapped_column(String(20), nullable=True)

    created_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), nullable=False
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), onupdate=func.now(), nullable=False
    )
