"""Add conversions table

Revision ID: 5b3c1a2f8d10
Revises: e6eaede720aa
Create Date: 2025-10-06 12:00:00.000000

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


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


def upgrade() -> None:
    op.create_table(
        'conversions',
        sa.Column('id', sa.Integer(), primary_key=True, autoincrement=True),
        sa.Column('source_event_media_id', sa.Integer(), nullable=False),
        sa.Column('target_format', sa.String(length=10), nullable=False),
        sa.Column('target_path', sa.String(length=512), nullable=True),
        sa.Column('status', sa.Enum('pending', 'processing', 'ready', 'failed', name='conversionstatus'),
                  nullable=False, server_default='pending'),
        sa.Column('file_hash', sa.String(length=64), nullable=True),
        sa.Column('started_at', sa.TIMESTAMP(timezone=True), nullable=True),
        sa.Column('completed_at', sa.TIMESTAMP(timezone=True), nullable=True),
        sa.Column('error_message', sa.Text(), nullable=True),
        sa.ForeignKeyConstraint(['source_event_media_id'], ['event_media.id'],
                                name='fk_conversions_event_media', ondelete='CASCADE'),
    )

    op.create_index('ix_conv_source_event_media_id', 'conversions', ['source_event_media_id'])
    op.create_index('ix_conversions_target_format', 'conversions', ['target_format'])
    op.create_index('ix_conv_status_target', 'conversions', ['status', 'target_format'])
    op.create_index('ix_conv_source_target', 'conversions', ['source_event_media_id', 'target_format'])

    op.create_unique_constraint('uq_conv_source_target_hash', 'conversions',
                                ['source_event_media_id', 'target_format', 'file_hash'])


def downgrade() -> None:
    op.drop_constraint('uq_conv_source_target_hash', 'conversions', type_='unique')
    op.drop_index('ix_conv_source_target', table_name='conversions')
    op.drop_index('ix_conv_status_target', table_name='conversions')
    op.drop_index('ix_conversions_target_format', table_name='conversions')
    op.drop_index('ix_conv_source_event_media_id', table_name='conversions')
    op.drop_table('conversions')
