"""add_iam_enforcement_tables

Creates tables for IAM enforcement with approval workflows:
- organization_settings: per-org enforcement config
- approval_rules: who can approve what
- approval_requests: approval request lifecycle
Also updates policy_associations CHECK constraint to include 'role' entity type.

Revision ID: add_iam_enforcement
Revises: add_data_ingestion_sources
Create Date: 2026-02-11 12:00:00.000000

"""
from typing import Sequence, Union

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

# revision identifiers, used by Alembic.
revision: str = 'add_iam_enforcement'
down_revision: Union[str, Sequence[str], None] = 'add_data_ingestion_sources'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    """Create IAM enforcement tables and update policy_associations."""

    # 1. organization_settings
    op.create_table(
        'organization_settings',
        sa.Column('organization_id', sa.String(255), primary_key=True),
        sa.Column('enforcement_enabled', sa.Boolean(), nullable=False, server_default=sa.text("false")),
        sa.Column('enforcement_mode', sa.String(50), nullable=False, server_default=sa.text("'monitoring'")),
        sa.Column('default_policy_id', sa.String(255), nullable=True),
        sa.Column('created_at', sa.DateTime(), nullable=True, server_default=sa.text("now()")),
        sa.Column('updated_at', sa.DateTime(), nullable=True, server_default=sa.text("now()")),
        schema='public',
    )

    # 2. approval_rules
    op.create_table(
        'approval_rules',
        sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True, server_default=sa.text("gen_random_uuid()")),
        sa.Column('organization_id', sa.String(255), nullable=False),
        sa.Column('name', sa.String(255), nullable=False),
        sa.Column('description', sa.Text(), nullable=True),
        sa.Column('scope_type', sa.String(50), nullable=False),
        sa.Column('scope_value', sa.String(255), nullable=True),
        sa.Column('approver_type', sa.String(50), nullable=False),
        sa.Column('approver_value', sa.JSON(), nullable=False),
        sa.Column('auto_approve_roles', sa.JSON(), nullable=True),
        sa.Column('require_reason', sa.Boolean(), nullable=False, server_default=sa.text("false")),
        sa.Column('timeout_minutes', sa.Integer(), nullable=False, server_default=sa.text("1440")),
        sa.Column('enabled', sa.Boolean(), nullable=False, server_default=sa.text("true")),
        sa.Column('priority', sa.Integer(), nullable=False, server_default=sa.text("0")),
        sa.Column('created_at', sa.DateTime(), nullable=True, server_default=sa.text("now()")),
        sa.Column('updated_at', sa.DateTime(), nullable=True, server_default=sa.text("now()")),
        schema='public',
    )
    op.create_index('idx_approval_rules_org', 'approval_rules', ['organization_id'], schema='public')
    op.create_index('idx_approval_rules_scope', 'approval_rules', ['scope_type', 'scope_value'], schema='public')
    op.create_index('idx_approval_rules_enabled', 'approval_rules', ['enabled'], schema='public')
    op.create_index('idx_approval_rules_priority', 'approval_rules', [sa.text('priority DESC')], schema='public')

    # 3. approval_requests
    op.create_table(
        'approval_requests',
        sa.Column('id', postgresql.UUID(as_uuid=True), primary_key=True, server_default=sa.text("gen_random_uuid()")),
        sa.Column('organization_id', sa.String(255), nullable=False),
        sa.Column('execution_id', sa.String(255), nullable=False),
        sa.Column('rule_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('status', sa.String(50), nullable=False, server_default=sa.text("'pending'")),
        sa.Column('requester_email', sa.String(255), nullable=True),
        sa.Column('requester_id', sa.String(255), nullable=True),
        sa.Column('tool_name', sa.String(255), nullable=False),
        sa.Column('tool_args', sa.JSON(), nullable=True),
        sa.Column('risk_level', sa.String(50), nullable=True),
        sa.Column('enforcement_context', sa.JSON(), nullable=True),
        sa.Column('approver_emails', sa.JSON(), nullable=True),
        sa.Column('approved_by_email', sa.String(255), nullable=True),
        sa.Column('approved_by_name', sa.String(255), nullable=True),
        sa.Column('rejection_reason', sa.Text(), nullable=True),
        sa.Column('resolved_at', sa.DateTime(), nullable=True),
        sa.Column('expires_at', sa.DateTime(), nullable=True),
        sa.Column('created_at', sa.DateTime(), nullable=True, server_default=sa.text("now()")),
        sa.Column('updated_at', sa.DateTime(), nullable=True, server_default=sa.text("now()")),
        schema='public',
    )
    op.create_index('idx_approval_requests_org', 'approval_requests', ['organization_id'], schema='public')
    op.create_index('idx_approval_requests_execution', 'approval_requests', ['execution_id'], schema='public')
    op.create_index('idx_approval_requests_status', 'approval_requests', ['status'], schema='public')
    op.create_index('idx_approval_requests_requester', 'approval_requests', ['requester_email'], schema='public')
    op.create_index('idx_approval_requests_created', 'approval_requests', [sa.text('created_at DESC')], schema='public')

    # 4. Update policy_associations CHECK constraint to include 'role'
    op.drop_constraint('policy_associations_entity_type_check', 'policy_associations', schema='public')
    op.create_check_constraint(
        'policy_associations_entity_type_check',
        'policy_associations',
        "entity_type IN ('agent', 'team', 'environment', 'role')",
        schema='public',
    )


def downgrade() -> None:
    """Drop IAM enforcement tables and revert policy_associations constraint."""

    # Revert policy_associations constraint
    op.drop_constraint('policy_associations_entity_type_check', 'policy_associations', schema='public')
    op.create_check_constraint(
        'policy_associations_entity_type_check',
        'policy_associations',
        "entity_type IN ('agent', 'team', 'environment')",
        schema='public',
    )

    op.drop_table('approval_requests', schema='public')
    op.drop_table('approval_rules', schema='public')
    op.drop_table('organization_settings', schema='public')
