"""make_stock_management_fields_nullable

Revision ID: make_stock_fields_nullable
Revises: add_local_production_support
Create Date: 2025-11-08 12:00:00.000000

"""
from alembic import op
import sqlalchemy as sa

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


def upgrade() -> None:
    """Make stock management fields nullable to simplify onboarding

    These fields (low_stock_threshold, reorder_point, reorder_quantity) are now optional
    during onboarding and can be configured later based on actual usage patterns.
    """

    # Make low_stock_threshold nullable
    op.alter_column('ingredients', 'low_stock_threshold',
                    existing_type=sa.Float(),
                    nullable=True,
                    existing_nullable=False)

    # Make reorder_point nullable
    op.alter_column('ingredients', 'reorder_point',
                    existing_type=sa.Float(),
                    nullable=True,
                    existing_nullable=False)

    # Make reorder_quantity nullable
    op.alter_column('ingredients', 'reorder_quantity',
                    existing_type=sa.Float(),
                    nullable=True,
                    existing_nullable=False)


def downgrade() -> None:
    """Revert stock management fields to NOT NULL

    WARNING: This will fail if any records have NULL values in these fields.
    You must set default values before running this downgrade.
    """

    # Set default values for any NULL records before making fields NOT NULL
    op.execute("""
        UPDATE ingredients
        SET low_stock_threshold = 10.0
        WHERE low_stock_threshold IS NULL
    """)

    op.execute("""
        UPDATE ingredients
        SET reorder_point = 20.0
        WHERE reorder_point IS NULL
    """)

    op.execute("""
        UPDATE ingredients
        SET reorder_quantity = 50.0
        WHERE reorder_quantity IS NULL
    """)

    # Make fields NOT NULL again
    op.alter_column('ingredients', 'low_stock_threshold',
                    existing_type=sa.Float(),
                    nullable=False,
                    existing_nullable=True)

    op.alter_column('ingredients', 'reorder_point',
                    existing_type=sa.Float(),
                    nullable=False,
                    existing_nullable=True)

    op.alter_column('ingredients', 'reorder_quantity',
                    existing_type=sa.Float(),
                    nullable=False,
                    existing_nullable=True)
