"""Move storage configuration from ingredient to batch level

Revision ID: 004_move_storage_config_to_batch
Revises: 003_add_production_stage_enum
Create Date: 2025-01-17 10:00:00.000000

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '004_move_storage_config_to_batch'
down_revision = '003_add_production_stage_enum'
branch_labels = None
depends_on = None


def upgrade():
    """Move storage configuration from ingredients to stock batches"""

    # Add batch-specific storage columns to stock table
    op.add_column('stock', sa.Column('requires_refrigeration', sa.Boolean(), default=False))
    op.add_column('stock', sa.Column('requires_freezing', sa.Boolean(), default=False))
    op.add_column('stock', sa.Column('storage_temperature_min', sa.Float(), nullable=True))
    op.add_column('stock', sa.Column('storage_temperature_max', sa.Float(), nullable=True))
    op.add_column('stock', sa.Column('storage_humidity_max', sa.Float(), nullable=True))
    op.add_column('stock', sa.Column('shelf_life_days', sa.Integer(), nullable=True))
    op.add_column('stock', sa.Column('storage_instructions', sa.Text(), nullable=True))

    # Migrate existing data from ingredients to stock batches
    # This will copy the ingredient-level storage config to all existing stock batches
    op.execute("""
        UPDATE stock
        SET
            requires_refrigeration = i.requires_refrigeration,
            requires_freezing = i.requires_freezing,
            storage_temperature_min = i.storage_temperature_min,
            storage_temperature_max = i.storage_temperature_max,
            storage_humidity_max = i.storage_humidity_max,
            shelf_life_days = i.shelf_life_days,
            storage_instructions = i.storage_instructions
        FROM ingredients i
        WHERE stock.ingredient_id = i.id
    """)

    # Remove storage configuration columns from ingredients table
    # Keep only shelf_life_days as default value
    op.drop_column('ingredients', 'requires_refrigeration')
    op.drop_column('ingredients', 'requires_freezing')
    op.drop_column('ingredients', 'storage_temperature_min')
    op.drop_column('ingredients', 'storage_temperature_max')
    op.drop_column('ingredients', 'storage_humidity_max')
    op.drop_column('ingredients', 'storage_instructions')


def downgrade():
    """Revert storage configuration back to ingredient level"""

    # Add storage configuration columns back to ingredients table
    op.add_column('ingredients', sa.Column('requires_refrigeration', sa.Boolean(), default=False))
    op.add_column('ingredients', sa.Column('requires_freezing', sa.Boolean(), default=False))
    op.add_column('ingredients', sa.Column('storage_temperature_min', sa.Float(), nullable=True))
    op.add_column('ingredients', sa.Column('storage_temperature_max', sa.Float(), nullable=True))
    op.add_column('ingredients', sa.Column('storage_humidity_max', sa.Float(), nullable=True))
    op.add_column('ingredients', sa.Column('storage_instructions', sa.Text(), nullable=True))

    # Migrate data back from stock to ingredients (use most common values per ingredient)
    op.execute("""
        UPDATE ingredients
        SET
            requires_refrigeration = COALESCE(
                (SELECT bool_or(s.requires_refrigeration) FROM stock s WHERE s.ingredient_id = ingredients.id),
                false
            ),
            requires_freezing = COALESCE(
                (SELECT bool_or(s.requires_freezing) FROM stock s WHERE s.ingredient_id = ingredients.id),
                false
            ),
            storage_temperature_min = (
                SELECT MIN(s.storage_temperature_min) FROM stock s WHERE s.ingredient_id = ingredients.id
            ),
            storage_temperature_max = (
                SELECT MAX(s.storage_temperature_max) FROM stock s WHERE s.ingredient_id = ingredients.id
            ),
            storage_humidity_max = (
                SELECT MAX(s.storage_humidity_max) FROM stock s WHERE s.ingredient_id = ingredients.id
            ),
            storage_instructions = (
                SELECT s.storage_instructions FROM stock s
                WHERE s.ingredient_id = ingredients.id
                AND s.storage_instructions IS NOT NULL
                LIMIT 1
            )
    """)

    # Remove batch-specific storage columns from stock table
    op.drop_column('stock', 'requires_refrigeration')
    op.drop_column('stock', 'requires_freezing')
    op.drop_column('stock', 'storage_temperature_min')
    op.drop_column('stock', 'storage_temperature_max')
    op.drop_column('stock', 'storage_humidity_max')
    op.drop_column('stock', 'shelf_life_days')
    op.drop_column('stock', 'storage_instructions')