"""Merge heads and add RLS to whatsapp_account + whatsapp_template.

Revision ID: 0025_merge_heads_and_rls_whatsapp_tables
Revises: 0024_merge_rls_whatsapp, 0024_add_conversation_context_enabled
Create Date: 2026-03-26 22:30:00.000000

"""

from collections.abc import Sequence

from alembic import op

# revision identifiers, used by Alembic.
revision: str = "0025_merge_heads_and_rls_whatsapp_tables"
down_revision: str | None = (
    "0024_merge_rls_whatsapp",
    "0024_add_conversation_context_enabled",
)
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None

# WhatsApp tables that extend TenantModel but were missing from 0023
_WHATSAPP_TABLES: list[str] = [
    "whatsapp_account",
    "whatsapp_template",
]


def upgrade() -> None:
    for table in _WHATSAPP_TABLES:
        op.execute(f'ALTER TABLE "{table}" ENABLE ROW LEVEL SECURITY')
        op.execute(f'ALTER TABLE "{table}" FORCE ROW LEVEL SECURITY')
        op.execute(f'DROP POLICY IF EXISTS tenant_isolation ON "{table}"')
        op.execute(
            f'CREATE POLICY tenant_isolation ON "{table}" '
            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 table in reversed(_WHATSAPP_TABLES):
        op.execute(f'DROP POLICY IF EXISTS tenant_isolation ON "{table}"')
        op.execute(f'ALTER TABLE "{table}" DISABLE ROW LEVEL SECURITY')
