"""Initial inventory tables

Revision ID: 001
Revises: 
Create Date: 2025-01-15 10:00:00.000000

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

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


def upgrade() -> None:
    # Create enum types
    op.execute("""
        CREATE TYPE unitofmeasure AS ENUM (
            'kg', 'g', 'l', 'ml', 'units', 'pcs', 'pkg', 'bags', 'boxes'
        );
    """)
    
    op.execute("""
        CREATE TYPE ingredientcategory AS ENUM (
            'flour', 'yeast', 'dairy', 'eggs', 'sugar', 'fats', 'salt', 
            'spices', 'additives', 'packaging', 'cleaning', 'other'
        );
    """)
    
    op.execute("""
        CREATE TYPE stockmovementtype AS ENUM (
            'purchase', 'production_use', 'adjustment', 'waste', 
            'transfer', 'return', 'initial_stock'
        );
    """)

    # Create ingredients table
    op.create_table(
        'ingredients',
        sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('name', sa.String(255), nullable=False),
        sa.Column('sku', sa.String(100), nullable=True),
        sa.Column('barcode', sa.String(50), nullable=True),
        sa.Column('category', sa.Enum('flour', 'yeast', 'dairy', 'eggs', 'sugar', 'fats', 'salt', 'spices', 'additives', 'packaging', 'cleaning', 'other', name='ingredientcategory'), nullable=False),
        sa.Column('subcategory', sa.String(100), nullable=True),
        sa.Column('description', sa.Text(), nullable=True),
        sa.Column('brand', sa.String(100), nullable=True),
        sa.Column('unit_of_measure', sa.Enum('kg', 'g', 'l', 'ml', 'units', 'pcs', 'pkg', 'bags', 'boxes', name='unitofmeasure'), nullable=False),
        sa.Column('package_size', sa.Float(), nullable=True),
        sa.Column('average_cost', sa.Numeric(10, 2), nullable=True),
        sa.Column('last_purchase_price', sa.Numeric(10, 2), nullable=True),
        sa.Column('standard_cost', sa.Numeric(10, 2), nullable=True),
        sa.Column('low_stock_threshold', sa.Float(), nullable=False, server_default='10.0'),
        sa.Column('reorder_point', sa.Float(), nullable=False, server_default='20.0'),
        sa.Column('reorder_quantity', sa.Float(), nullable=False, server_default='50.0'),
        sa.Column('max_stock_level', sa.Float(), nullable=True),
        sa.Column('requires_refrigeration', sa.Boolean(), nullable=True, server_default='false'),
        sa.Column('requires_freezing', sa.Boolean(), nullable=True, server_default='false'),
        sa.Column('storage_temperature_min', sa.Float(), nullable=True),
        sa.Column('storage_temperature_max', sa.Float(), nullable=True),
        sa.Column('storage_humidity_max', sa.Float(), nullable=True),
        sa.Column('shelf_life_days', sa.Integer(), nullable=True),
        sa.Column('storage_instructions', sa.Text(), nullable=True),
        sa.Column('is_active', sa.Boolean(), nullable=True, server_default='true'),
        sa.Column('is_perishable', sa.Boolean(), nullable=True, server_default='false'),
        sa.Column('allergen_info', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
        sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
        sa.Column('created_by', postgresql.UUID(as_uuid=True), nullable=True),
        sa.PrimaryKeyConstraint('id')
    )
    
    # Create stock table
    op.create_table(
        'stock',
        sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('ingredient_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('batch_number', sa.String(100), nullable=True),
        sa.Column('lot_number', sa.String(100), nullable=True),
        sa.Column('supplier_batch_ref', sa.String(100), nullable=True),
        sa.Column('current_quantity', sa.Float(), nullable=False, server_default='0.0'),
        sa.Column('reserved_quantity', sa.Float(), nullable=False, server_default='0.0'),
        sa.Column('available_quantity', sa.Float(), nullable=False, server_default='0.0'),
        sa.Column('received_date', sa.DateTime(timezone=True), nullable=True),
        sa.Column('expiration_date', sa.DateTime(timezone=True), nullable=True),
        sa.Column('best_before_date', sa.DateTime(timezone=True), nullable=True),
        sa.Column('unit_cost', sa.Numeric(10, 2), nullable=True),
        sa.Column('total_cost', sa.Numeric(10, 2), nullable=True),
        sa.Column('storage_location', sa.String(100), nullable=True),
        sa.Column('warehouse_zone', sa.String(50), nullable=True),
        sa.Column('shelf_position', sa.String(50), nullable=True),
        sa.Column('is_available', sa.Boolean(), nullable=True, server_default='true'),
        sa.Column('is_expired', sa.Boolean(), nullable=True, server_default='false'),
        sa.Column('quality_status', sa.String(20), nullable=True, server_default='good'),
        sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
        sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
        sa.ForeignKeyConstraint(['ingredient_id'], ['ingredients.id'], ),
        sa.PrimaryKeyConstraint('id')
    )
    
    # Create stock_movements table
    op.create_table(
        'stock_movements',
        sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('ingredient_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('stock_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('movement_type', sa.Enum('purchase', 'production_use', 'adjustment', 'waste', 'transfer', 'return', 'initial_stock', name='stockmovementtype'), nullable=False),
        sa.Column('quantity', sa.Float(), nullable=False),
        sa.Column('unit_cost', sa.Numeric(10, 2), nullable=True),
        sa.Column('total_cost', sa.Numeric(10, 2), nullable=True),
        sa.Column('quantity_before', sa.Float(), nullable=True),
        sa.Column('quantity_after', sa.Float(), nullable=True),
        sa.Column('reference_number', sa.String(100), nullable=True),
        sa.Column('supplier_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('notes', sa.Text(), nullable=True),
        sa.Column('reason_code', sa.String(50), nullable=True),
        sa.Column('movement_date', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
        sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
        sa.Column('created_by', postgresql.UUID(as_uuid=True), nullable=True),
        sa.ForeignKeyConstraint(['ingredient_id'], ['ingredients.id'], ),
        sa.ForeignKeyConstraint(['stock_id'], ['stock.id'], ),
        sa.PrimaryKeyConstraint('id')
    )
    
    # Create stock_alerts table
    op.create_table(
        'stock_alerts',
        sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('ingredient_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('stock_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('alert_type', sa.String(50), nullable=False),
        sa.Column('severity', sa.String(20), nullable=False, server_default='medium'),
        sa.Column('title', sa.String(255), nullable=False),
        sa.Column('message', sa.Text(), nullable=False),
        sa.Column('current_quantity', sa.Float(), nullable=True),
        sa.Column('threshold_value', sa.Float(), nullable=True),
        sa.Column('expiration_date', sa.DateTime(timezone=True), nullable=True),
        sa.Column('is_active', sa.Boolean(), nullable=True, server_default='true'),
        sa.Column('is_acknowledged', sa.Boolean(), nullable=True, server_default='false'),
        sa.Column('acknowledged_by', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('acknowledged_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('is_resolved', sa.Boolean(), nullable=True, server_default='false'),
        sa.Column('resolved_by', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('resolved_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('resolution_notes', sa.Text(), nullable=True),
        sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
        sa.Column('updated_at', sa.DateTime(timezone=True), server_default=sa.text('now()'), nullable=False),
        sa.ForeignKeyConstraint(['ingredient_id'], ['ingredients.id'], ),
        sa.ForeignKeyConstraint(['stock_id'], ['stock.id'], ),
        sa.PrimaryKeyConstraint('id')
    )

    # Create indexes for ingredients table
    op.create_index('idx_ingredients_tenant_name', 'ingredients', ['tenant_id', 'name'], unique=True)
    op.create_index('idx_ingredients_tenant_sku', 'ingredients', ['tenant_id', 'sku'])
    op.create_index('idx_ingredients_barcode', 'ingredients', ['barcode'])
    op.create_index('idx_ingredients_category', 'ingredients', ['tenant_id', 'category', 'is_active'])
    op.create_index('idx_ingredients_stock_levels', 'ingredients', ['tenant_id', 'low_stock_threshold', 'reorder_point'])
    
    # Create indexes for stock table
    op.create_index('idx_stock_tenant_ingredient', 'stock', ['tenant_id', 'ingredient_id'])
    op.create_index('idx_stock_expiration', 'stock', ['tenant_id', 'expiration_date', 'is_available'])
    op.create_index('idx_stock_batch', 'stock', ['tenant_id', 'batch_number'])
    op.create_index('idx_stock_low_levels', 'stock', ['tenant_id', 'current_quantity', 'is_available'])
    op.create_index('idx_stock_quality', 'stock', ['tenant_id', 'quality_status', 'is_available'])
    
    # Create indexes for stock_movements table
    op.create_index('idx_movements_tenant_date', 'stock_movements', ['tenant_id', 'movement_date'])
    op.create_index('idx_movements_tenant_ingredient', 'stock_movements', ['tenant_id', 'ingredient_id', 'movement_date'])
    op.create_index('idx_movements_type', 'stock_movements', ['tenant_id', 'movement_type', 'movement_date'])
    op.create_index('idx_movements_reference', 'stock_movements', ['reference_number'])
    op.create_index('idx_movements_supplier', 'stock_movements', ['supplier_id', 'movement_date'])
    
    # Create indexes for stock_alerts table
    op.create_index('idx_alerts_tenant_active', 'stock_alerts', ['tenant_id', 'is_active', 'created_at'])
    op.create_index('idx_alerts_type_severity', 'stock_alerts', ['alert_type', 'severity', 'is_active'])
    op.create_index('idx_alerts_ingredient', 'stock_alerts', ['ingredient_id', 'is_active'])
    op.create_index('idx_alerts_unresolved', 'stock_alerts', ['tenant_id', 'is_resolved', 'is_active'])


def downgrade() -> None:
    # Drop indexes
    op.drop_index('idx_alerts_unresolved', table_name='stock_alerts')
    op.drop_index('idx_alerts_ingredient', table_name='stock_alerts')
    op.drop_index('idx_alerts_type_severity', table_name='stock_alerts')
    op.drop_index('idx_alerts_tenant_active', table_name='stock_alerts')
    
    op.drop_index('idx_movements_supplier', table_name='stock_movements')
    op.drop_index('idx_movements_reference', table_name='stock_movements')
    op.drop_index('idx_movements_type', table_name='stock_movements')
    op.drop_index('idx_movements_tenant_ingredient', table_name='stock_movements')
    op.drop_index('idx_movements_tenant_date', table_name='stock_movements')
    
    op.drop_index('idx_stock_quality', table_name='stock')
    op.drop_index('idx_stock_low_levels', table_name='stock')
    op.drop_index('idx_stock_batch', table_name='stock')
    op.drop_index('idx_stock_expiration', table_name='stock')
    op.drop_index('idx_stock_tenant_ingredient', table_name='stock')
    
    op.drop_index('idx_ingredients_stock_levels', table_name='ingredients')
    op.drop_index('idx_ingredients_category', table_name='ingredients')
    op.drop_index('idx_ingredients_barcode', table_name='ingredients')
    op.drop_index('idx_ingredients_tenant_sku', table_name='ingredients')
    op.drop_index('idx_ingredients_tenant_name', table_name='ingredients')
    
    # Drop tables
    op.drop_table('stock_alerts')
    op.drop_table('stock_movements')
    op.drop_table('stock')
    op.drop_table('ingredients')
    
    # Drop enum types
    op.execute("DROP TYPE stockmovementtype;")
    op.execute("DROP TYPE ingredientcategory;")
    op.execute("DROP TYPE unitofmeasure;")