"""Add events table and auto_events_enabled to marathons

Revision ID: 004_add_events
Revises: 003_create_admin
Create Date: 2024-12-14

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision: str = '004_add_events'
down_revision: Union[str, None] = '003_create_admin'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


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

    if 'events' not in tables:
        op.create_table(
            'events',
            sa.Column('id', sa.Integer(), nullable=False),
            sa.Column('marathon_id', sa.Integer(), nullable=False),
            sa.Column('type', sa.String(30), nullable=False),
            sa.Column('start_time', sa.DateTime(), nullable=False),
            sa.Column('end_time', sa.DateTime(), nullable=True),
            sa.Column('is_active', sa.Boolean(), nullable=False, server_default='true'),
            sa.Column('created_by_id', sa.Integer(), nullable=True),
            sa.Column('data', sa.JSON(), nullable=True),
            sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()),
            sa.PrimaryKeyConstraint('id'),
            sa.ForeignKeyConstraint(['marathon_id'], ['marathons.id'], ondelete='CASCADE'),
            sa.ForeignKeyConstraint(['created_by_id'], ['users.id'], ondelete='SET NULL'),
        )

    # Create index if it doesn't exist
    indexes = [idx['name'] for idx in inspector.get_indexes('events')]
    if 'ix_events_marathon_id' not in indexes:
        op.create_index('ix_events_marathon_id', 'events', ['marathon_id'])

    # Add auto_events_enabled to marathons if it doesn't exist
    columns = [col['name'] for col in inspector.get_columns('marathons')]
    if 'auto_events_enabled' not in columns:
        op.add_column(
            'marathons',
            sa.Column('auto_events_enabled', sa.Boolean(), nullable=False, server_default='true')
        )


def downgrade() -> None:
    op.drop_column('marathons', 'auto_events_enabled')
    op.drop_index('ix_events_marathon_id', table_name='events')
    op.drop_table('events')
