"""Wire RLS into the support-inbox pack.

v1.0.0 declared support_ticket/support_message with no rls_enabled and no
owner concept at all -- any caller with query access could list every
customer's tickets and messages, not just their own. Same gap client-portal
had (109_client_portal_rls.py) and saas-membership had (122), fixed the same
way here: add rls_enabled: true to both entities. Going forward, a ticket or
message created through the signed-in requester's own Authorization header
gets its owner_user_id auto-stamped by Cloud, exactly like any other
rls_enabled entity -- no new data field needed for that.

Unlike client-portal/saas-membership, support_ticket never carried an
app_user_id (or any other) field identifying its owner -- only
requester_email, which is a display/contact field, not a verified identity
link. There is therefore no fully deterministic way to backfill ownership on
tickets created before this migration; see
scripts/backfill_support_inbox_ownership.py, which does a best-effort
requester_email -> Cloud auth user match and explicitly SKIPS (never guesses)
any ticket whose email doesn't resolve to exactly one project user. Run once
per already-installed project after reinstalling, same as the client-portal
backfill.

Revision ID: 123
Revises: 122
"""
from datetime import datetime, timezone

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

revision = "123"
down_revision = "122"
branch_labels = None
depends_on = None

feature_packs = sa.table(
    "feature_packs",
    sa.column("slug", sa.String),
    sa.column("version", sa.String),
    sa.column("composition", postgresql.JSONB),
    sa.column("updated_at", sa.DateTime(timezone=True)),
)

_SUPPORT_TICKET_ENTITY_V1 = {
    "entity_key": "support_ticket",
    "name": "Support Ticket",
    "plural_name": "Support Tickets",
    "schema": {
        "fields": [
            {"key": "subject", "name": "Subject", "type": "text", "required": True},
            {"key": "requester_email", "name": "Requester Email", "type": "text", "required": True, "indexed": True},
            {"key": "status", "name": "Status", "type": "select",
             "options": ["open", "pending", "resolved", "closed"], "required": True, "indexed": True},
            {"key": "priority", "name": "Priority", "type": "select",
             "options": ["low", "normal", "high"], "indexed": True},
            {"key": "assigned_to", "name": "Assigned To", "type": "text", "indexed": True},
        ],
    },
}

_SUPPORT_MESSAGE_ENTITY_V1 = {
    "entity_key": "support_message",
    "name": "Support Message",
    "plural_name": "Support Messages",
    "schema": {
        "fields": [
            {"key": "ticket_record_id", "name": "Ticket", "type": "relation",
             "relation_entity_key": "support_ticket", "required": True, "indexed": True},
            {"key": "sender_type", "name": "Sender Type", "type": "select",
             "options": ["owner", "customer"], "required": True, "indexed": True},
            {"key": "body", "name": "Body", "type": "text", "required": True},
        ],
    },
}

_SUPPORT_TICKET_ENTITY_V1_1 = {**_SUPPORT_TICKET_ENTITY_V1, "rls_enabled": True}
_SUPPORT_MESSAGE_ENTITY_V1_1 = {**_SUPPORT_MESSAGE_ENTITY_V1, "rls_enabled": True}

_COMPOSITION_V1_1 = {
    "function_slugs": [],
    "entities": [_SUPPORT_TICKET_ENTITY_V1_1, _SUPPORT_MESSAGE_ENTITY_V1_1],
    "connector_actions": [],
    "requires": [],
}

_COMPOSITION_V1_0 = {
    "function_slugs": [],
    "entities": [_SUPPORT_TICKET_ENTITY_V1, _SUPPORT_MESSAGE_ENTITY_V1],
    "connector_actions": [],
    "requires": [],
}


def upgrade() -> None:
    op.execute(
        sa.update(feature_packs)
        .where(feature_packs.c.slug == "support-inbox")
        .values(
            version="1.1.0",
            composition=_COMPOSITION_V1_1,
            updated_at=datetime.now(timezone.utc),
        )
    )


def downgrade() -> None:
    op.execute(
        sa.update(feature_packs)
        .where(feature_packs.c.slug == "support-inbox")
        .values(
            version="1.0.0",
            composition=_COMPOSITION_V1_0,
            updated_at=datetime.now(timezone.utc),
        )
    )
