"""Create user_preferences table for per-user UI settings.

Revision ID: 0028
Revises: 0027_unify_company_to_contact
Create Date: 2026-07-23

Changes:
- Create user_preferences table with tenant_id, user_id, key, value (JSONB)
- Unique constraint on (tenant_id, user_id, key)
- Indexes on tenant_id+user_id and user_id
- tenant_id column (required by TenantMixin / RLS)
- created_at, updated_at, deleted_at columns (TimestampMixin + SoftDeleteMixin)
"""

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import JSONB, UUID as PGUUID


revision = "0028_user_preferences"
down_revision = "0027_unify_company_to_contact"


def upgrade():
    op.create_table(
        "user_preferences",
        sa.Column("id", PGUUID(as_uuid=True), primary_key=True, server_default=sa.text("gen_random_uuid()")),
        sa.Column("tenant_id", PGUUID(as_uuid=True), sa.ForeignKey("tenants.id", ondelete="CASCADE"), nullable=False),
        sa.Column("user_id", PGUUID(as_uuid=True), sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False),
        sa.Column("key", sa.String(100), nullable=False),
        sa.Column("value", JSONB, nullable=False, server_default=sa.text("'{}'::jsonb")),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True),
        sa.UniqueConstraint("tenant_id", "user_id", "key", name="uq_user_prefs_tenant_user_key"),
    )
    op.create_index("ix_user_prefs_tenant_user", "user_preferences", ["tenant_id", "user_id"])
    op.create_index("ix_user_prefs_user_id", "user_preferences", ["user_id"])
    op.create_index("ix_user_prefs_tenant_id", "user_preferences", ["tenant_id"])


def downgrade():
    op.drop_index("ix_user_prefs_tenant_id", table_name="user_preferences")
    op.drop_index("ix_user_prefs_user_id", table_name="user_preferences")
    op.drop_index("ix_user_prefs_tenant_user", table_name="user_preferences")
    op.drop_table("user_preferences")
