"""RBAC 004 - Create merchant_invites table

PRD-008 RBAC — Migration 4 of 7

Creates the merchant_invites table for tracking pending team invitations.
Raw tokens are never stored — only the SHA-256 hash is persisted.
Invite links expire after a configurable TTL (default 72 hours).

Revision ID: rbac004d5e6f7a
Revises: rbac003c4d5e6f
Create Date: 2026-03-19 00:00:04.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


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


def upgrade() -> None:
    op.create_table(
        'merchant_invites',
        sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
        sa.Column('merchant_id', sa.Integer(), nullable=False),
        sa.Column('email', sa.String(length=255), nullable=False),
        sa.Column('role_id', sa.Integer(), nullable=False),
        sa.Column('token_hash', sa.String(length=64), nullable=False),
        sa.Column('invited_by', sa.Integer(), nullable=False),
        sa.Column('expires_at', sa.DateTime(), nullable=False),
        sa.Column('accepted_at', sa.DateTime(), nullable=True),
        sa.Column('cancelled_at', sa.DateTime(), nullable=True),
        sa.Column('created_at', sa.DateTime(), server_default=sa.func.now(), nullable=True),
        sa.ForeignKeyConstraint(['merchant_id'], ['merchants.id'], name='fk_merchant_invites_merchant_id'),
        sa.ForeignKeyConstraint(['role_id'], ['roles.id'], name='fk_merchant_invites_role_id'),
        sa.ForeignKeyConstraint(['invited_by'], ['users.id'], name='fk_merchant_invites_invited_by'),
        sa.PrimaryKeyConstraint('id'),
    )
    # Primary lookup index: resolve invite by hashed token from email link
    op.create_index('ix_merchant_invites_token_hash', 'merchant_invites', ['token_hash'], unique=False)
    # Support listing all invites for a merchant in the admin UI
    op.create_index('ix_merchant_invites_merchant_id', 'merchant_invites', ['merchant_id'], unique=False)


def downgrade() -> None:
    op.drop_index('ix_merchant_invites_merchant_id', table_name='merchant_invites')
    op.drop_index('ix_merchant_invites_token_hash', table_name='merchant_invites')
    op.drop_table('merchant_invites')
