"""add_kitchen_completed_at

Revision ID: 3ced2f231be1
Revises: 4ff085c3804a
Create Date: 2025-05-13 15:39:14.844000

"""
import logging

from alembic import op, context
import sqlalchemy as sa


logger = logging.getLogger(__name__)


# revision identifiers, used by Alembic.
revision = '3ced2f231be1'
down_revision = '4ff085c3804a'
branch_labels = None
depends_on = None

first_agent_version = '25.5.15.1'


def upgrade():
    connection = op.get_bind()
    inspector = sa.inspect(connection)
    tables = set(inspector.get_table_names())

    try:
        op.execute('PRAGMA foreign_keys = "0";')
        if 'ticket_kitchen' in tables:
            logger.info("Table 'ticket_kitchen' already exists, skipping its migration...")
        else:
            op.create_table(
                'ticket_kitchen',
                sa.Column('ticket_id', sa.String(length=64), primary_key=True),
                sa.Column('completed_at', sa.DateTime, nullable=True),

                sa.ForeignKeyConstraint(
                    ['ticket_id'],
                    ['tickets.id'],
                    name='fk_ticket_kitchen_tickets',
                    onupdate='CASCADE',
                    ondelete='CASCADE'
                ),
            )

        if 'held_ticket_kitchen' in tables:
            logger.info("Table 'held_ticket_kitchen' already exists, skipping its migration...")
        else:
            op.create_table(
                'held_ticket_kitchen',
                sa.Column('ticket_id', sa.String(length=64)),
                sa.Column('completed_at', sa.DateTime, nullable=True),

                sa.ForeignKeyConstraint(
                    ['ticket_id'],
                    ['held_tickets.id'],
                    name='fk_held_ticket_kitchen_tickets',
                    onupdate='CASCADE',
                    ondelete='CASCADE'
                ),
            )
    finally:
        op.execute('PRAGMA foreign_keys = "1";')


def downgrade():
    current_context = context.get_context()
    inspector = sa.inspect(current_context.connection)
    tables = set(inspector.get_table_names())
    try:
        op.execute('PRAGMA foreign_keys = "0";')

        if 'ticket_kitchen' in tables:
            op.drop_table('ticket_kitchen')

        if 'held_ticket_kitchen' in tables:
            op.drop_table('held_ticket_kitchen')

    finally:
        op.execute('PRAGMA foreign_keys = "1";')
