"""add_local_production_support

Revision ID: add_local_production_support
Revises: e7fcea67bf4e
Create Date: 2025-10-29 14:00:00.000000

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = 'add_local_production_support'
down_revision = 'e7fcea67bf4e'
branch_labels = None
depends_on = None


def upgrade() -> None:
    """Add local production support columns to ingredients table"""

    # Add produced_locally column
    op.add_column('ingredients', sa.Column(
        'produced_locally',
        sa.Boolean(),
        nullable=False,
        server_default='false',
        comment='If true, ingredient is produced in-house and requires BOM explosion'
    ))

    # Add recipe_id column for BOM explosion
    op.add_column('ingredients', sa.Column(
        'recipe_id',
        postgresql.UUID(as_uuid=True),
        nullable=True,
        comment='Links to recipe for BOM explosion when ingredient is produced locally'
    ))

    # Create index for efficient querying of locally-produced ingredients
    op.create_index(
        'ix_ingredients_produced_locally',
        'ingredients',
        ['produced_locally'],
        unique=False
    )

    # Create index for recipe_id lookups
    op.create_index(
        'ix_ingredients_recipe_id',
        'ingredients',
        ['recipe_id'],
        unique=False
    )

    # Add check constraint: if produced_locally is true, recipe_id should be set
    # Note: This is a soft constraint - we allow NULL recipe_id even if produced_locally=true
    # to support gradual data migration and edge cases
    # op.create_check_constraint(
    #     'ck_ingredients_local_production',
    #     'ingredients',
    #     'produced_locally = false OR recipe_id IS NOT NULL'
    # )


def downgrade() -> None:
    """Remove local production support columns from ingredients table"""

    # Drop check constraint
    # op.drop_constraint('ck_ingredients_local_production', 'ingredients', type_='check')

    # Drop indexes
    op.drop_index('ix_ingredients_recipe_id', table_name='ingredients')
    op.drop_index('ix_ingredients_produced_locally', table_name='ingredients')

    # Drop columns
    op.drop_column('ingredients', 'recipe_id')
    op.drop_column('ingredients', 'produced_locally')
