"""Enable RLS and create tenant isolation policies on tenant-scoped tables.

Revision ID: 0023_enable_rls_and_policies
Revises: 0022_add_restaurant_id_to_indirect_tables
Create Date: 2026-03-12
"""

from collections.abc import Sequence

from alembic import op

revision: str = "0023_enable_rls_and_policies"
down_revision: str | None = "0022_add_restaurant_id_to_indirect_tables"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None

TENANT_TABLES: list[str] = [
    "zone",
    "floor_table",
    "reservation",
    "customer",
    "order",
    "menu_item",
    "service_block",
    "service_block_override",
    "table_combination",
    "conversation",
    "knowledge_document",
    "faq_entry",
    "common_question",
    "chair",
    "order_item",
    "message",
    "service_block_zones",
    "combined_chair_config",
    "notification",
]


def upgrade() -> None:
    for t in TENANT_TABLES:
        op.execute(f'ALTER TABLE "{t}" ENABLE ROW LEVEL SECURITY')
        op.execute(f'ALTER TABLE "{t}" FORCE ROW LEVEL SECURITY')
        # Use the same policy name per table; policy namespace is per table
        op.execute(f'DROP POLICY IF EXISTS tenant_isolation ON "{t}"')
        op.execute(
            f'CREATE POLICY tenant_isolation ON "{t}" '
            f"FOR ALL "
            f"USING (restaurant_id = current_setting("
            "'"
            "app.tenant_id"
            "'"
            ", true)) "
            f"WITH CHECK (restaurant_id = current_setting("
            "'"
            "app.tenant_id"
            "'"
            ", true))"
        )


def downgrade() -> None:
    for t in TENANT_TABLES:
        op.execute(f'DROP POLICY IF EXISTS tenant_isolation ON "{t}"')
        op.execute(f'ALTER TABLE "{t}" NO FORCE ROW LEVEL SECURITY')
        op.execute(f'ALTER TABLE "{t}" DISABLE ROW LEVEL SECURITY')
