"""Add is_event_assignment and event_id to assignments for Common Enemy support

Revision ID: 007_add_event_assignment_fields
Revises: 006_add_swap_requests
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 = '007_add_event_assignment_fields'
down_revision: Union[str, None] = '006_add_swap_requests'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Add is_event_assignment column with default False
    conn = op.get_bind()
    inspector = sa.inspect(conn)
    columns = [col['name'] for col in inspector.get_columns('assignments')]

    if 'is_event_assignment' not in columns:
        op.add_column(
            'assignments',
            sa.Column('is_event_assignment', sa.Boolean(), nullable=False, server_default=sa.false())
        )
        op.create_index('ix_assignments_is_event_assignment', 'assignments', ['is_event_assignment'])

    if 'event_id' not in columns:
        op.add_column(
            'assignments',
            sa.Column('event_id', sa.Integer(), nullable=True)
        )
        op.create_foreign_key(
            'fk_assignments_event_id',
            'assignments',
            'events',
            ['event_id'],
            ['id'],
            ondelete='SET NULL'
        )
        op.create_index('ix_assignments_event_id', 'assignments', ['event_id'])


def downgrade() -> None:
    op.drop_index('ix_assignments_event_id', table_name='assignments')
    op.drop_constraint('fk_assignments_event_id', 'assignments', type_='foreignkey')
    op.drop_column('assignments', 'event_id')
    op.drop_index('ix_assignments_is_event_assignment', table_name='assignments')
    op.drop_column('assignments', 'is_event_assignment')
