"""RBAC 007 - Create merchant_audit_log table

PRD-008 RBAC — Migration 7 of 7

Creates the merchant_audit_log table — an append-only record of all RBAC
actions performed within a merchant account (role assignments, ownership
transfers, invitations sent/cancelled, team member removals, etc.).

Indexes support the three primary access patterns:
  - Merchant admin listing their own audit log (merchant_id)
  - Filtering by action type (action)
  - Sorting/paging by time (created_at)

Revision ID: rbac007a8b9c0d
Revises: rbac006f7a8b9c
Create Date: 2026-03-19 00:00:07.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


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


def upgrade() -> None:
    op.create_table(
        'merchant_audit_log',
        sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
        sa.Column('merchant_id', sa.Integer(), nullable=False),
        sa.Column('actor_user_id', sa.Integer(), nullable=False),
        sa.Column('action', sa.String(length=100), nullable=False),
        sa.Column('target_user_id', sa.Integer(), nullable=True),
        sa.Column('target_role_id', sa.Integer(), nullable=True),
        sa.Column('metadata', sa.JSON(), nullable=True),
        sa.Column('created_at', sa.DateTime(), server_default=sa.func.now(), nullable=True),
        sa.ForeignKeyConstraint(['merchant_id'], ['merchants.id'], name='fk_merchant_audit_log_merchant_id'),
        sa.ForeignKeyConstraint(['actor_user_id'], ['users.id'], name='fk_merchant_audit_log_actor_user_id'),
        sa.ForeignKeyConstraint(['target_user_id'], ['users.id'], name='fk_merchant_audit_log_target_user_id'),
        sa.ForeignKeyConstraint(['target_role_id'], ['roles.id'], name='fk_merchant_audit_log_target_role_id'),
        sa.PrimaryKeyConstraint('id'),
    )
    op.create_index(
        'ix_merchant_audit_log_merchant_id',
        'merchant_audit_log',
        ['merchant_id'],
        unique=False,
    )
    op.create_index(
        'ix_merchant_audit_log_action',
        'merchant_audit_log',
        ['action'],
        unique=False,
    )
    op.create_index(
        'ix_merchant_audit_log_created_at',
        'merchant_audit_log',
        ['created_at'],
        unique=False,
    )


def downgrade() -> None:
    op.drop_index('ix_merchant_audit_log_created_at', table_name='merchant_audit_log')
    op.drop_index('ix_merchant_audit_log_action', table_name='merchant_audit_log')
    op.drop_index('ix_merchant_audit_log_merchant_id', table_name='merchant_audit_log')
    op.drop_table('merchant_audit_log')
