"""Add swap_requests table for two-sided swap confirmation

Revision ID: 006_add_swap_requests
Revises: 005_assignment_event
Create Date: 2024-12-15

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision: str = '006_add_swap_requests'
down_revision: Union[str, None] = '005_add_assignment_event_type'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Create swap_requests table if it doesn't exist
    conn = op.get_bind()
    inspector = sa.inspect(conn)
    tables = inspector.get_table_names()

    if 'swap_requests' not in tables:
        op.create_table(
            'swap_requests',
            sa.Column('id', sa.Integer(), nullable=False),
            sa.Column('event_id', sa.Integer(), nullable=False),
            sa.Column('from_participant_id', sa.Integer(), nullable=False),
            sa.Column('to_participant_id', sa.Integer(), nullable=False),
            sa.Column('from_assignment_id', sa.Integer(), nullable=False),
            sa.Column('to_assignment_id', sa.Integer(), nullable=False),
            sa.Column('status', sa.String(20), nullable=False, server_default='pending'),
            sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()),
            sa.Column('responded_at', sa.DateTime(), nullable=True),
            sa.PrimaryKeyConstraint('id'),
            sa.ForeignKeyConstraint(['event_id'], ['events.id'], ondelete='CASCADE'),
            sa.ForeignKeyConstraint(['from_participant_id'], ['participants.id'], ondelete='CASCADE'),
            sa.ForeignKeyConstraint(['to_participant_id'], ['participants.id'], ondelete='CASCADE'),
            sa.ForeignKeyConstraint(['from_assignment_id'], ['assignments.id'], ondelete='CASCADE'),
            sa.ForeignKeyConstraint(['to_assignment_id'], ['assignments.id'], ondelete='CASCADE'),
        )
        op.create_index('ix_swap_requests_event_id', 'swap_requests', ['event_id'])
        op.create_index('ix_swap_requests_from_participant_id', 'swap_requests', ['from_participant_id'])
        op.create_index('ix_swap_requests_to_participant_id', 'swap_requests', ['to_participant_id'])


def downgrade() -> None:
    op.drop_index('ix_swap_requests_to_participant_id', table_name='swap_requests')
    op.drop_index('ix_swap_requests_from_participant_id', table_name='swap_requests')
    op.drop_index('ix_swap_requests_event_id', table_name='swap_requests')
    op.drop_table('swap_requests')
