"""User Preference model — per-user UI settings stored as key/value JSONB, tenant-scoped."""

from __future__ import annotations

import uuid
from typing import Any

from sqlalchemy import ForeignKey, Index, String, UniqueConstraint
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column

from app.core.db import Base, TenantMixin


class UserPreference(Base, TenantMixin):
    """Per-user preference entry — stores a single UI preference as JSONB value.

    Keys are arbitrary strings (e.g. 'sidebar_collapsed', 'theme', 'active_tab').
    Values are JSONB to support complex preference structures.
    """

    __tablename__ = "user_preferences"
    __table_args__ = (
        UniqueConstraint(
            "tenant_id",
            "user_id",
            "key",
            name="uq_user_prefs_tenant_user_key",
        ),
        Index(
            "ix_user_prefs_tenant_user",
            "tenant_id",
            "user_id",
        ),
    )

    id: Mapped[uuid.UUID] = mapped_column(
        PGUUID(as_uuid=True), primary_key=True, default=uuid.uuid4
    )
    user_id: Mapped[uuid.UUID] = mapped_column(
        PGUUID(as_uuid=True),
        ForeignKey("users.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    key: Mapped[str] = mapped_column(String(100), nullable=False)
    value: Mapped[Any] = mapped_column(JSONB, nullable=False, default=dict)
