"""general chat: one global flag row, usage-count index, analytics view

Revision ID: b8c9d0e1f2a3
Revises: a7b8c9d0e1f2
Create Date: 2026-10-07

Follow-ups to the general-chat migrations before them (plus: general chat is
switched ON - see the UPDATE in upgrade()):

1. uq_feature_flags_feature_scope does not stop a second GLOBAL row: the
   global row's scope_id is NULL, and Postgres treats NULLs as distinct in a
   unique constraint. A partial unique index on the NULL-scope rows does.
   Any duplicates already there are removed first, keeping the oldest - the
   row feature_flag_service reads.

2. An index for the per-user general-chat allowance (FR-08), which counts a
   user's recent general answers on every general-chat-enabled request.
   hr_query_logs had no index on company_id at all.

3. hr_query_analytics: the reporting view FR-09 asks for, WITHOUT the query
   and response columns, so metrics can be read without exposing what
   people typed.
"""
from alembic import op
import sqlalchemy as sa


revision = "b8c9d0e1f2a3"
down_revision = "a7b8c9d0e1f2"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.execute(
        "DELETE FROM feature_flags f USING feature_flags g "
        "WHERE f.feature = g.feature AND f.scope_type = g.scope_type "
        "AND f.scope_id IS NULL AND g.scope_id IS NULL AND f.id > g.id"
    )
    op.create_index(
        "uq_feature_flags_global", "feature_flags", ["feature", "scope_type"],
        unique=True, postgresql_where=sa.text("scope_id IS NULL"),
    )

    # General chat ships ENABLED (product decision, 2026-10-07). f1a2b3c4d5e6
    # first seeded the global row as false, so a database that already ran it
    # is switched on here; a fresh one is seeded true there. Not undone on
    # downgrade - the switch belongs to whoever flips it after this.
    op.execute(
        "UPDATE feature_flags SET enabled = true, updated_at = now() "
        "WHERE feature = 'general_chat' AND scope_type = 'global' AND scope_id IS NULL"
    )
    op.execute(
        "INSERT INTO feature_flags (feature, scope_type, scope_id, enabled) "
        "SELECT 'general_chat', 'global', NULL, true WHERE NOT EXISTS ("
        "SELECT 1 FROM feature_flags WHERE feature = 'general_chat' "
        "AND scope_type = 'global' AND scope_id IS NULL)"
    )

    op.create_index(
        "ix_hr_query_logs_user_intent_created", "hr_query_logs",
        ["company_id", "intent", "created_at"],
    )

    op.execute("""
        CREATE VIEW hr_query_analytics AS
        SELECT id, created_at,
               company_id AS user_id,      -- hr_query_logs.company_id holds the USER id
               true_company_id AS tenant_id,
               company_name, role_id, user_type, conversation_id,
               intent, category, source, status, failure_stage,
               provider, model, total_time, ai_time
        FROM hr_query_logs
    """)


def downgrade() -> None:
    op.execute("DROP VIEW IF EXISTS hr_query_analytics")
    op.drop_index("ix_hr_query_logs_user_intent_created", table_name="hr_query_logs")
    op.drop_index("uq_feature_flags_global", table_name="feature_flags")
