"""add generic behavior, risk incident and subject restriction tables

Revision ID: risk_monitor_generic
Revises: drop_withdraw_active_uniq_idx
"""
from __future__ import annotations

from collections.abc import Sequence

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

from alembic import op

revision: str = "risk_monitor_generic"
down_revision: str | None = "drop_withdraw_active_uniq_idx"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None

_JSON = sa.JSON().with_variant(postgresql.JSONB(), "postgresql")
_RISK_MONITOR_PAGE = "risk-monitor"
_DEFAULT_RISK_MONITOR_ROLES = ("operator", "tech")


def _role_table() -> sa.TableClause:
    return sa.table(
        "admin_role",
        sa.column("name", sa.String),
        sa.column("pages", _JSON),
    )


def _add_default_role_permissions() -> None:
    """Grant the new page without replacing any existing role customisation."""
    role = _role_table()
    conn = op.get_bind()
    rows = conn.execute(
        sa.select(role.c.name, role.c.pages).where(
            role.c.name.in_(_DEFAULT_RISK_MONITOR_ROLES)
        )
    ).all()
    for name, pages in rows:
        current_pages = list(pages or [])
        if _RISK_MONITOR_PAGE not in current_pages:
            conn.execute(
                role.update()
                .where(role.c.name == name)
                .values(pages=[*current_pages, _RISK_MONITOR_PAGE])
            )


def _remove_default_role_permissions() -> None:
    role = _role_table()
    conn = op.get_bind()
    rows = conn.execute(
        sa.select(role.c.name, role.c.pages).where(
            role.c.name.in_(_DEFAULT_RISK_MONITOR_ROLES)
        )
    ).all()
    for name, pages in rows:
        current_pages = list(pages or [])
        if _RISK_MONITOR_PAGE in current_pages:
            conn.execute(
                role.update()
                .where(role.c.name == name)
                .values(
                    pages=[
                        page
                        for page in current_pages
                        if page != _RISK_MONITOR_PAGE
                    ]
                )
            )


def upgrade() -> None:
    op.create_table(
        "behavior_event",
        sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
        sa.Column("event_type", sa.String(length=64), nullable=False),
        sa.Column("subject_type", sa.String(length=32), nullable=False),
        sa.Column("subject_id", sa.String(length=128), nullable=False),
        sa.Column("user_id", sa.Integer(), nullable=True),
        sa.Column("device_id", sa.String(length=128), nullable=True),
        sa.Column("device_model", sa.String(length=128), nullable=True),
        sa.Column("phone", sa.String(length=20), nullable=True),
        sa.Column("client_ip", sa.String(length=64), nullable=True),
        sa.Column("outcome", sa.String(length=24), nullable=False),
        sa.Column("reason", sa.String(length=256), nullable=True),
        sa.Column("details", sa.JSON(), nullable=True),
        sa.Column("occurred_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=sa.text("(CURRENT_TIMESTAMP)"),
            nullable=False,
        ),
        sa.PrimaryKeyConstraint("id"),
    )
    op.create_index("ix_behavior_event_occurred_at", "behavior_event", ["occurred_at"])
    op.create_index(
        "ix_behavior_event_type_time", "behavior_event", ["event_type", "occurred_at"]
    )
    op.create_index(
        "ix_behavior_event_subject_time",
        "behavior_event",
        ["subject_type", "subject_id", "occurred_at"],
    )
    op.create_index(
        "ix_behavior_event_user_time", "behavior_event", ["user_id", "occurred_at"]
    )

    op.create_table(
        "risk_incident",
        sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
        sa.Column("rule_code", sa.String(length=64), nullable=False),
        sa.Column("event_type", sa.String(length=64), nullable=False),
        sa.Column("subject_type", sa.String(length=32), nullable=False),
        sa.Column("subject_id", sa.String(length=128), nullable=False),
        sa.Column("window_key", sa.String(length=64), nullable=False),
        sa.Column("window_start", sa.DateTime(timezone=True), nullable=False),
        sa.Column("window_end", sa.DateTime(timezone=True), nullable=False),
        sa.Column("first_event_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("triggered_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("last_event_at", sa.DateTime(timezone=True), nullable=False),
        sa.Column("event_count", sa.Integer(), nullable=False),
        sa.Column("status", sa.String(length=24), nullable=False),
        sa.Column("action_reason", sa.String(length=256), nullable=True),
        sa.Column("handled_by", sa.Integer(), nullable=True),
        sa.Column("handled_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("details", sa.JSON(), nullable=True),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=sa.text("(CURRENT_TIMESTAMP)"),
            nullable=False,
        ),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            server_default=sa.text("(CURRENT_TIMESTAMP)"),
            nullable=False,
        ),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint(
            "rule_code",
            "subject_type",
            "subject_id",
            "window_key",
            name="uq_risk_incident_rule_subject_window",
        ),
    )
    op.create_index(
        "ix_risk_incident_rule_status",
        "risk_incident",
        ["rule_code", "status", "triggered_at"],
    )
    op.create_index(
        "ix_risk_incident_subject",
        "risk_incident",
        ["subject_type", "subject_id", "triggered_at"],
    )

    op.create_table(
        "subject_restriction",
        sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
        sa.Column("subject_type", sa.String(length=32), nullable=False),
        sa.Column("subject_id", sa.String(length=128), nullable=False),
        sa.Column("scope", sa.String(length=32), nullable=False),
        sa.Column("active", sa.Boolean(), server_default=sa.true(), nullable=False),
        sa.Column("reason", sa.String(length=256), nullable=True),
        sa.Column("incident_id", sa.Integer(), nullable=True),
        sa.Column("created_by", sa.Integer(), nullable=True),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            server_default=sa.text("(CURRENT_TIMESTAMP)"),
            nullable=False,
        ),
        sa.Column("revoked_by", sa.Integer(), nullable=True),
        sa.Column("revoked_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("details", sa.JSON(), nullable=True),
        sa.PrimaryKeyConstraint("id"),
        sa.UniqueConstraint(
            "subject_type",
            "subject_id",
            "scope",
            name="uq_subject_restriction_subject_scope",
        ),
    )
    op.create_index(
        "ix_subject_restriction_lookup",
        "subject_restriction",
        ["subject_type", "subject_id", "scope", "active"],
    )
    _add_default_role_permissions()


def downgrade() -> None:
    _remove_default_role_permissions()
    op.drop_index("ix_subject_restriction_lookup", table_name="subject_restriction")
    op.drop_table("subject_restriction")
    op.drop_index("ix_risk_incident_subject", table_name="risk_incident")
    op.drop_index("ix_risk_incident_rule_status", table_name="risk_incident")
    op.drop_table("risk_incident")
    op.drop_index("ix_behavior_event_user_time", table_name="behavior_event")
    op.drop_index("ix_behavior_event_subject_time", table_name="behavior_event")
    op.drop_index("ix_behavior_event_type_time", table_name="behavior_event")
    op.drop_index("ix_behavior_event_occurred_at", table_name="behavior_event")
    op.drop_table("behavior_event")
