"""unified initial procurement schema with all fields from all migrations

Revision ID: 001_unified_initial_schema
Revises:
Create Date: 2025-11-27 12:00:00.000000+00:00

Complete procurement service schema including:
- Procurement plans and requirements
- Purchase orders and items (with reasoning_data for i18n JTBD dashboard)
- Deliveries and delivery items
- Supplier invoices
- Replenishment planning
- Inventory projections
- Supplier allocations and selection history
- Audit logs
- Internal transfer fields
"""
from typing import Sequence, Union

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

# revision identifiers, used by Alembic.
revision: str = '001_unified_initial_schema'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Create PostgreSQL enum types first
    # PurchaseOrderStatus enum
    purchaseorderstatus_enum = postgresql.ENUM(
        'draft', 'pending_approval', 'approved', 'sent_to_supplier',
        'confirmed', 'partially_received', 'completed', 'cancelled', 'disputed',
        name='purchaseorderstatus',
        create_type=False
    )
    purchaseorderstatus_enum.create(op.get_bind(), checkfirst=True)

    # DeliveryStatus enum
    deliverystatus_enum = postgresql.ENUM(
        'scheduled', 'in_transit', 'out_for_delivery', 'delivered',
        'partially_delivered', 'failed_delivery', 'returned',
        name='deliverystatus',
        create_type=False
    )
    deliverystatus_enum.create(op.get_bind(), checkfirst=True)

    # InvoiceStatus enum
    invoicestatus_enum = postgresql.ENUM(
        'pending', 'approved', 'paid', 'overdue', 'disputed', 'cancelled',
        name='invoicestatus',
        create_type=False
    )
    invoicestatus_enum.create(op.get_bind(), checkfirst=True)

    # ========================================================================
    # PROCUREMENT PLANNING TABLES
    # ========================================================================

    # Create procurement_plans table
    op.create_table('procurement_plans',
        sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('plan_number', sa.String(length=50), nullable=False),
        sa.Column('plan_date', sa.Date(), nullable=False),
        sa.Column('plan_period_start', sa.Date(), nullable=False),
        sa.Column('plan_period_end', sa.Date(), nullable=False),
        sa.Column('planning_horizon_days', sa.Integer(), nullable=False, server_default='14'),
        sa.Column('status', sa.String(length=50), nullable=False, server_default='draft'),
        sa.Column('plan_type', sa.String(length=50), nullable=False, server_default='regular'),
        sa.Column('priority', sa.String(length=20), nullable=False, server_default='normal'),
        sa.Column('business_model', sa.String(length=50), nullable=True),
        sa.Column('procurement_strategy', sa.String(length=50), nullable=False, server_default='just_in_time'),
        sa.Column('total_requirements', sa.Integer(), nullable=False, server_default='0'),
        sa.Column('total_estimated_cost', sa.Numeric(precision=12, scale=2), nullable=False, server_default='0.00'),
        sa.Column('total_approved_cost', sa.Numeric(precision=12, scale=2), nullable=False, server_default='0.00'),
        sa.Column('cost_variance', sa.Numeric(precision=12, scale=2), nullable=False, server_default='0.00'),
        sa.Column('total_demand_orders', sa.Integer(), nullable=False, server_default='0'),
        sa.Column('total_demand_quantity', sa.Numeric(precision=12, scale=3), nullable=False, server_default='0.000'),
        sa.Column('total_production_requirements', sa.Numeric(precision=12, scale=3), nullable=False, server_default='0.00'),
        sa.Column('safety_stock_buffer', sa.Numeric(precision=5, scale=2), nullable=False, server_default='20.00'),
        sa.Column('primary_suppliers_count', sa.Integer(), nullable=False, server_default='0'),
        sa.Column('backup_suppliers_count', sa.Integer(), nullable=False, server_default='0'),
        sa.Column('supplier_diversification_score', sa.Numeric(precision=3, scale=1), nullable=True),
        sa.Column('supply_risk_level', sa.String(length=20), nullable=False, server_default='low'),
        sa.Column('demand_forecast_confidence', sa.Numeric(precision=3, scale=1), nullable=True),
        sa.Column('seasonality_adjustment', sa.Numeric(precision=5, scale=2), nullable=False, server_default='0.00'),
        sa.Column('approved_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('approved_by', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('execution_started_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('execution_completed_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('fulfillment_rate', sa.Numeric(precision=5, scale=2), nullable=True),
        sa.Column('on_time_delivery_rate', sa.Numeric(precision=5, scale=2), nullable=True),
        sa.Column('cost_accuracy', sa.Numeric(precision=5, scale=2), nullable=True),
        sa.Column('quality_score', sa.Numeric(precision=3, scale=1), nullable=True),
        sa.Column('source_orders', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('production_schedules', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('inventory_snapshots', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('forecast_data', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('stakeholder_notifications', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('approval_workflow', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('special_requirements', sa.Text(), nullable=True),
        sa.Column('seasonal_adjustments', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('emergency_provisions', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('erp_reference', sa.String(length=100), nullable=True),
        sa.Column('supplier_portal_reference', sa.String(length=100), 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()'), onupdate=sa.text('now()'), nullable=False),
        sa.Column('created_by', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('updated_by', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('plan_metadata', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_procurement_plans_plan_date'), 'procurement_plans', ['plan_date'], unique=False)
    op.create_index(op.f('ix_procurement_plans_plan_number'), 'procurement_plans', ['plan_number'], unique=True)
    op.create_index(op.f('ix_procurement_plans_status'), 'procurement_plans', ['status'], unique=False)
    op.create_index(op.f('ix_procurement_plans_tenant_id'), 'procurement_plans', ['tenant_id'], unique=False)

    # Create procurement_requirements table
    op.create_table('procurement_requirements',
        sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('plan_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('requirement_number', sa.String(length=50), nullable=False),
        sa.Column('product_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('product_name', sa.String(length=200), nullable=False),
        sa.Column('product_sku', sa.String(length=100), nullable=True),
        sa.Column('product_category', sa.String(length=100), nullable=True),
        sa.Column('product_type', sa.String(length=50), nullable=False, server_default='ingredient'),
        sa.Column('is_locally_produced', sa.Boolean(), nullable=False, server_default='false'),
        sa.Column('recipe_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('parent_requirement_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('bom_explosion_level', sa.Integer(), nullable=False, server_default='0'),
        sa.Column('required_quantity', sa.Numeric(precision=12, scale=3), nullable=False),
        sa.Column('unit_of_measure', sa.String(length=50), nullable=False),
        sa.Column('safety_stock_quantity', sa.Numeric(precision=12, scale=3), nullable=False, server_default='0.000'),
        sa.Column('total_quantity_needed', sa.Numeric(precision=12, scale=3), nullable=False),
        sa.Column('current_stock_level', sa.Numeric(precision=12, scale=3), nullable=False, server_default='0.00'),
        sa.Column('reserved_stock', sa.Numeric(precision=12, scale=3), nullable=False, server_default='0.00'),
        sa.Column('available_stock', sa.Numeric(precision=12, scale=3), nullable=False, server_default='0.000'),
        sa.Column('net_requirement', sa.Numeric(precision=12, scale=3), nullable=False),
        sa.Column('order_demand', sa.Numeric(precision=12, scale=3), nullable=False, server_default='0.000'),
        sa.Column('production_demand', sa.Numeric(precision=12, scale=3), nullable=False, server_default='0.00'),
        sa.Column('forecast_demand', sa.Numeric(precision=12, scale=3), nullable=False, server_default='0.00'),
        sa.Column('buffer_demand', sa.Numeric(precision=12, scale=3), nullable=False, server_default='0.00'),
        sa.Column('preferred_supplier_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('backup_supplier_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('supplier_name', sa.String(length=200), nullable=True),
        sa.Column('supplier_lead_time_days', sa.Integer(), nullable=True),
        sa.Column('minimum_order_quantity', sa.Numeric(precision=12, scale=3), nullable=True),
        sa.Column('estimated_unit_cost', sa.Numeric(precision=10, scale=4), nullable=True),
        sa.Column('estimated_total_cost', sa.Numeric(precision=12, scale=2), nullable=True),
        sa.Column('last_purchase_cost', sa.Numeric(precision=10, scale=4), nullable=True),
        sa.Column('cost_variance', sa.Numeric(precision=10, scale=2), nullable=False, server_default='0.00'),
        sa.Column('required_by_date', sa.Date(), nullable=False),
        sa.Column('lead_time_buffer_days', sa.Integer(), nullable=False, server_default='1'),
        sa.Column('suggested_order_date', sa.Date(), nullable=False),
        sa.Column('latest_order_date', sa.Date(), nullable=False),
        sa.Column('shelf_life_days', sa.Integer(), nullable=True),
        sa.Column('status', sa.String(length=50), nullable=False, server_default='pending'),
        sa.Column('priority', sa.String(length=20), nullable=False, server_default='normal'),
        sa.Column('risk_level', sa.String(length=20), nullable=False, server_default='low'),
        sa.Column('purchase_order_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('purchase_order_number', sa.String(length=50), nullable=True),
        sa.Column('ordered_quantity', sa.Numeric(precision=12, scale=3), nullable=False, server_default='0.000'),
        sa.Column('ordered_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('expected_delivery_date', sa.Date(), nullable=True),
        sa.Column('actual_delivery_date', sa.Date(), nullable=True),
        sa.Column('received_quantity', sa.Numeric(precision=12, scale=3), nullable=False, server_default='0.000'),
        sa.Column('delivery_status', sa.String(length=50), nullable=False, server_default='pending'),
        sa.Column('fulfillment_rate', sa.Numeric(precision=5, scale=2), nullable=True),
        sa.Column('on_time_delivery', sa.Boolean(), nullable=True),
        sa.Column('quality_rating', sa.Numeric(precision=3, scale=1), nullable=True),
        sa.Column('source_orders', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('source_production_batches', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('demand_analysis', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('quality_specifications', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('special_requirements', sa.Text(), nullable=True),
        sa.Column('storage_requirements', sa.String(length=200), nullable=True),
        sa.Column('calculation_method', sa.String(length=100), nullable=True),
        sa.Column('ai_suggested_quantity', sa.Numeric(precision=12, scale=3), nullable=True),
        sa.Column('adjusted_quantity', sa.Numeric(precision=12, scale=3), nullable=True),
        sa.Column('adjustment_reason', sa.Text(), nullable=True),
        sa.Column('price_tier_applied', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('supplier_minimum_applied', sa.Boolean(), nullable=False, server_default='false'),
        sa.Column('storage_limit_applied', sa.Boolean(), nullable=False, server_default='false'),
        sa.Column('reorder_rule_applied', sa.Boolean(), nullable=False, server_default='false'),
        sa.Column('approved_quantity', sa.Numeric(precision=12, scale=3), nullable=True),
        sa.Column('approved_cost', sa.Numeric(precision=12, scale=2), nullable=True),
        sa.Column('approved_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('approved_by', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('procurement_notes', sa.Text(), nullable=True),
        sa.Column('supplier_communication', 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()'), onupdate=sa.text('now()'), nullable=False),
        sa.Column('requirement_metadata', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.ForeignKeyConstraint(['plan_id'], ['procurement_plans.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_procurement_requirements_plan_id'), 'procurement_requirements', ['plan_id'], unique=False)
    op.create_index(op.f('ix_procurement_requirements_product_id'), 'procurement_requirements', ['product_id'], unique=False)
    op.create_index(op.f('ix_procurement_requirements_requirement_number'), 'procurement_requirements', ['requirement_number'], unique=False)
    op.create_index(op.f('ix_procurement_requirements_status'), 'procurement_requirements', ['status'], unique=False)

    # ========================================================================
    # PURCHASE ORDER TABLES
    # ========================================================================

    # Create purchase_orders table (with reasoning_data for i18n and internal transfer fields)
    op.create_table('purchase_orders',
        sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('supplier_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('po_number', sa.String(length=50), nullable=False),
        sa.Column('reference_number', sa.String(length=100), nullable=True),
        sa.Column('procurement_plan_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('status', purchaseorderstatus_enum, nullable=False, server_default='draft'),
        sa.Column('priority', sa.String(length=20), nullable=False, server_default='normal'),
        sa.Column('order_date', sa.DateTime(timezone=True), nullable=False, server_default=sa.text('now()')),
        sa.Column('required_delivery_date', sa.DateTime(timezone=True), nullable=True),
        sa.Column('estimated_delivery_date', sa.DateTime(timezone=True), nullable=True),
        sa.Column('expected_delivery_date', sa.DateTime(timezone=True), nullable=True),
        sa.Column('subtotal', sa.Numeric(precision=12, scale=2), nullable=False, server_default='0.00'),
        sa.Column('tax_amount', sa.Numeric(precision=12, scale=2), nullable=False, server_default='0.00'),
        sa.Column('shipping_cost', sa.Numeric(precision=10, scale=2), nullable=False, server_default='0.00'),
        sa.Column('discount_amount', sa.Numeric(precision=10, scale=2), nullable=False, server_default='0.00'),
        sa.Column('total_amount', sa.Numeric(precision=12, scale=2), nullable=False, server_default='0.00'),
        sa.Column('currency', sa.String(length=3), nullable=False, server_default='EUR'),
        sa.Column('delivery_address', sa.Text(), nullable=True),
        sa.Column('delivery_instructions', sa.Text(), nullable=True),
        sa.Column('delivery_contact', sa.String(length=200), nullable=True),
        sa.Column('delivery_phone', sa.String(length=30), nullable=True),
        sa.Column('requires_approval', sa.Boolean(), nullable=False, server_default='false'),
        sa.Column('approved_by', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('approved_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('auto_approved', sa.Boolean(), nullable=False, server_default='false'),
        sa.Column('auto_approval_rule_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('rejection_reason', sa.Text(), nullable=True),
        sa.Column('sent_to_supplier_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('supplier_confirmation_date', sa.DateTime(timezone=True), nullable=True),
        sa.Column('supplier_reference', sa.String(length=100), nullable=True),
        sa.Column('notes', sa.Text(), nullable=True),
        sa.Column('internal_notes', sa.Text(), nullable=True),
        sa.Column('terms_and_conditions', sa.Text(), nullable=True),
        # JTBD Dashboard: Structured reasoning for i18n support
        sa.Column('reasoning_data', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        # Internal transfer fields
        sa.Column('is_internal', sa.Boolean(), nullable=False, server_default='false'),
        sa.Column('source_tenant_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('destination_tenant_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('transfer_type', sa.String(length=50), 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()'), onupdate=sa.text('now()'), nullable=False),
        sa.Column('created_by', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('updated_by', postgresql.UUID(as_uuid=True), nullable=False),
        sa.ForeignKeyConstraint(['procurement_plan_id'], ['procurement_plans.id']),
        # Note: supplier_id references suppliers service - no FK constraint in microservices
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_purchase_orders_po_number'), 'purchase_orders', ['po_number'], unique=True)
    op.create_index(op.f('ix_purchase_orders_procurement_plan_id'), 'purchase_orders', ['procurement_plan_id'], unique=False)
    op.create_index(op.f('ix_purchase_orders_status'), 'purchase_orders', ['status'], unique=False)
    op.create_index(op.f('ix_purchase_orders_supplier_id'), 'purchase_orders', ['supplier_id'], unique=False)
    op.create_index(op.f('ix_purchase_orders_tenant_id'), 'purchase_orders', ['tenant_id'], unique=False)
    op.create_index('ix_purchase_orders_tenant_status', 'purchase_orders', ['tenant_id', 'status'], unique=False)
    op.create_index('ix_purchase_orders_tenant_plan', 'purchase_orders', ['tenant_id', 'procurement_plan_id'], unique=False)
    op.create_index('ix_purchase_orders_order_date', 'purchase_orders', ['order_date'], unique=False)
    op.create_index('ix_purchase_orders_delivery_date', 'purchase_orders', ['required_delivery_date'], unique=False)
    # Internal transfer indexes
    op.create_index('ix_purchase_orders_is_internal', 'purchase_orders', ['is_internal'])
    op.create_index('ix_purchase_orders_source_tenant', 'purchase_orders', ['source_tenant_id'])
    op.create_index('ix_purchase_orders_destination_tenant', 'purchase_orders', ['destination_tenant_id'])
    op.create_index('ix_po_internal_transfers', 'purchase_orders', ['tenant_id', 'is_internal', 'source_tenant_id'])

    # Create purchase_order_items table (with supplier_price_list_id)
    op.create_table('purchase_order_items',
        sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('purchase_order_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('procurement_requirement_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('inventory_product_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('supplier_price_list_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('product_code', sa.String(length=100), nullable=True),
        sa.Column('product_name', sa.String(length=200), nullable=False),
        sa.Column('ordered_quantity', sa.Numeric(precision=12, scale=3), nullable=False),
        sa.Column('unit_of_measure', sa.String(length=20), nullable=False),
        sa.Column('unit_price', sa.Numeric(precision=10, scale=4), nullable=False),
        sa.Column('line_total', sa.Numeric(precision=12, scale=2), nullable=False),
        sa.Column('received_quantity', sa.Numeric(precision=12, scale=3), nullable=False, server_default='0.000'),
        sa.Column('remaining_quantity', sa.Numeric(precision=12, scale=3), nullable=False, server_default='0.000'),
        sa.Column('quality_requirements', sa.Text(), nullable=True),
        sa.Column('item_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()'), onupdate=sa.text('now()'), nullable=False),
        sa.ForeignKeyConstraint(['procurement_requirement_id'], ['procurement_requirements.id']),
        sa.ForeignKeyConstraint(['purchase_order_id'], ['purchase_orders.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_purchase_order_items_inventory_product_id'), 'purchase_order_items', ['inventory_product_id'], unique=False)
    op.create_index(op.f('ix_purchase_order_items_procurement_requirement_id'), 'purchase_order_items', ['procurement_requirement_id'], unique=False)
    op.create_index(op.f('ix_purchase_order_items_purchase_order_id'), 'purchase_order_items', ['purchase_order_id'], unique=False)
    op.create_index(op.f('ix_purchase_order_items_supplier_price_list_id'), 'purchase_order_items', ['supplier_price_list_id'], unique=False)
    op.create_index(op.f('ix_purchase_order_items_tenant_id'), 'purchase_order_items', ['tenant_id'], unique=False)
    op.create_index('ix_po_items_tenant_po', 'purchase_order_items', ['tenant_id', 'purchase_order_id'], unique=False)
    op.create_index('ix_po_items_inventory_product', 'purchase_order_items', ['inventory_product_id'], unique=False)

    # ========================================================================
    # DELIVERY TABLES
    # ========================================================================

    # Create deliveries table
    op.create_table('deliveries',
        sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('purchase_order_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('supplier_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('delivery_number', sa.String(length=50), nullable=False),
        sa.Column('supplier_delivery_note', sa.String(length=10), nullable=True),
        sa.Column('status', deliverystatus_enum, nullable=False, server_default='scheduled'),
        sa.Column('scheduled_date', sa.DateTime(timezone=True), nullable=True),
        sa.Column('estimated_arrival', sa.DateTime(timezone=True), nullable=True),
        sa.Column('actual_arrival', sa.DateTime(timezone=True), nullable=True),
        sa.Column('completed_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('delivery_address', sa.Text(), nullable=True),
        sa.Column('delivery_contact', sa.String(200), nullable=True),
        sa.Column('delivery_phone', sa.String(30), nullable=True),
        sa.Column('carrier_name', sa.String(200), nullable=True),
        sa.Column('tracking_number', sa.String(100), nullable=True),
        sa.Column('inspection_passed', sa.Boolean(), nullable=True),
        sa.Column('inspection_notes', sa.Text(), nullable=True),
        sa.Column('quality_issues', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('received_by', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('received_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('notes', sa.Text(), nullable=True),
        sa.Column('photos', 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()'), onupdate=sa.text('now()'), nullable=False),
        sa.Column('created_by', postgresql.UUID(as_uuid=True), nullable=False),
        sa.ForeignKeyConstraint(['purchase_order_id'], ['purchase_orders.id'], ondelete='CASCADE'),
        # ... Note: supplier_id references suppliers service - no FK constraint in microservices
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_deliveries_delivery_number'), 'deliveries', ['delivery_number'], unique=True)
    op.create_index(op.f('ix_deliveries_purchase_order_id'), 'deliveries', ['purchase_order_id'], unique=False)
    op.create_index(op.f('ix_deliveries_status'), 'deliveries', ['status'], unique=False)
    op.create_index(op.f('ix_deliveries_supplier_id'), 'deliveries', ['supplier_id'], unique=False)
    op.create_index(op.f('ix_deliveries_tenant_id'), 'deliveries', ['tenant_id'], unique=False)
    op.create_index('ix_deliveries_scheduled_date', 'deliveries', ['scheduled_date'], unique=False)
    op.create_index('ix_deliveries_tenant_status', 'deliveries', ['tenant_id', 'status'], unique=False)

    # Create delivery_items table
    op.create_table('delivery_items',
        sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('delivery_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('purchase_order_item_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('inventory_product_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('ordered_quantity', sa.Numeric(precision=12, scale=3), nullable=False),
        sa.Column('delivered_quantity', sa.Numeric(precision=12, scale=3), nullable=False),
        sa.Column('accepted_quantity', sa.Numeric(precision=12, scale=3), nullable=False),
        sa.Column('rejected_quantity', sa.Numeric(precision=12, scale=3), nullable=False, server_default='0.000'),
        sa.Column('batch_lot_number', sa.String(length=100), nullable=True),
        sa.Column('expiry_date', sa.DateTime(timezone=True), nullable=True),
        sa.Column('quality_grade', sa.String(length=20), nullable=True),
        sa.Column('quality_issues', sa.Text(), nullable=True),
        sa.Column('rejection_reason', sa.Text(), nullable=True),
        sa.Column('item_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()'), onupdate=sa.text('now()'), nullable=False),
        sa.ForeignKeyConstraint(['delivery_id'], ['deliveries.id'], ondelete='CASCADE'),
        sa.ForeignKeyConstraint(['purchase_order_item_id'], ['purchase_order_items.id'], ondelete='CASCADE'),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_delivery_items_delivery_id'), 'delivery_items', ['delivery_id'], unique=False)
    op.create_index(op.f('ix_delivery_items_inventory_product_id'), 'delivery_items', ['inventory_product_id'], unique=False)
    op.create_index(op.f('ix_delivery_items_purchase_order_item_id'), 'delivery_items', ['purchase_order_item_id'], unique=False)
    op.create_index(op.f('ix_delivery_items_tenant_id'), 'delivery_items', ['tenant_id'], unique=False)
    op.create_index('ix_delivery_items_tenant_delivery', 'delivery_items', ['tenant_id', 'delivery_id'], unique=False)
    op.create_index('ix_delivery_items_inventory_product', 'delivery_items', ['inventory_product_id'], unique=False)

    # ========================================================================
    # INVOICE TABLES
    # ========================================================================

    # Create supplier_invoices table
    op.create_table('supplier_invoices',
        sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('supplier_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('purchase_order_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('invoice_number', sa.String(length=50), nullable=False),
        sa.Column('supplier_invoice_number', sa.String(length=100), nullable=False),
        sa.Column('status', invoicestatus_enum, nullable=False, server_default='pending'),
        sa.Column('invoice_date', sa.DateTime(timezone=True), nullable=False),
        sa.Column('due_date', sa.DateTime(timezone=True), nullable=False),
        sa.Column('received_date', sa.DateTime(timezone=True), nullable=False, server_default=sa.text('now()')),
        sa.Column('subtotal', sa.Numeric(precision=12, scale=2), nullable=False),
        sa.Column('tax_amount', sa.Numeric(precision=12, scale=2), nullable=False, server_default='0.00'),
        sa.Column('shipping_cost', sa.Numeric(precision=10, scale=2), nullable=False, server_default='0.00'),
        sa.Column('discount_amount', sa.Numeric(precision=10, scale=2), nullable=False, server_default='0.00'),
        sa.Column('total_amount', sa.Numeric(precision=12, scale=2), nullable=False),
        sa.Column('currency', sa.String(length=3), nullable=False, server_default='EUR'),
        sa.Column('paid_amount', sa.Numeric(precision=12, scale=2), nullable=False, server_default='0.00'),
        sa.Column('payment_date', sa.DateTime(timezone=True), nullable=True),
        sa.Column('payment_reference', sa.String(length=100), nullable=True),
        sa.Column('approved_by', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('approved_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('rejection_reason', sa.Text(), nullable=True),
        sa.Column('notes', sa.Text(), nullable=True),
        sa.Column('invoice_document_url', sa.String(length=500), 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()'), onupdate=sa.text('now()'), nullable=False),
        sa.Column('created_by', postgresql.UUID(as_uuid=True), nullable=False),
        sa.ForeignKeyConstraint(['purchase_order_id'], ['purchase_orders.id'], ondelete='SET NULL'),
        # Note: supplier_id references suppliers service - no FK constraint in microservices
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_supplier_invoices_invoice_number'), 'supplier_invoices', ['invoice_number'], unique=True)
    op.create_index(op.f('ix_supplier_invoices_purchase_order_id'), 'supplier_invoices', ['purchase_order_id'], unique=False)
    op.create_index(op.f('ix_supplier_invoices_status'), 'supplier_invoices', ['status'], unique=False)
    op.create_index(op.f('ix_supplier_invoices_supplier_id'), 'supplier_invoices', ['supplier_id'], unique=False)
    op.create_index(op.f('ix_supplier_invoices_tenant_id'), 'supplier_invoices', ['tenant_id'], unique=False)
    op.create_index('ix_invoices_due_date', 'supplier_invoices', ['due_date'], unique=False)
    op.create_index('ix_invoices_tenant_status', 'supplier_invoices', ['tenant_id', 'status'], unique=False)
    op.create_index('ix_invoices_tenant_supplier', 'supplier_invoices', ['tenant_id', 'supplier_id'], unique=False)

    # ========================================================================
    # REPLENISHMENT PLANNING TABLES
    # ========================================================================

    # Create replenishment_plans table
    op.create_table('replenishment_plans',
        sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('planning_date', sa.Date(), nullable=False),
        sa.Column('projection_horizon_days', sa.Integer(), nullable=False, server_default='7'),
        sa.Column('forecast_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('production_schedule_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('total_items', sa.Integer(), nullable=False, server_default='0'),
        sa.Column('urgent_items', sa.Integer(), nullable=False, server_default='0'),
        sa.Column('high_risk_items', sa.Integer(), nullable=False, server_default='0'),
        sa.Column('total_estimated_cost', sa.Numeric(12, 2), nullable=False, server_default='0'),
        sa.Column('status', sa.String(50), nullable=False, server_default='draft'),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=False, server_default=sa.text('now()')),
        sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
        sa.Column('executed_at', sa.DateTime(timezone=True), nullable=True),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index('ix_replenishment_plans_tenant_id', 'replenishment_plans', ['tenant_id'])
    op.create_index('ix_replenishment_plans_planning_date', 'replenishment_plans', ['planning_date'])
    op.create_index('ix_replenishment_plans_status', 'replenishment_plans', ['status'])

    # Create replenishment_plan_items table
    op.create_table('replenishment_plan_items',
        sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('replenishment_plan_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('ingredient_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('ingredient_name', sa.String(200), nullable=False),
        sa.Column('unit_of_measure', sa.String(20), nullable=False),
        sa.Column('base_quantity', sa.Numeric(12, 3), nullable=False),
        sa.Column('safety_stock_quantity', sa.Numeric(12, 3), nullable=False, server_default='0'),
        sa.Column('shelf_life_adjusted_quantity', sa.Numeric(12, 3), nullable=False),
        sa.Column('final_order_quantity', sa.Numeric(12, 3), nullable=False),
        sa.Column('order_date', sa.Date(), nullable=False),
        sa.Column('delivery_date', sa.Date(), nullable=False),
        sa.Column('required_by_date', sa.Date(), nullable=False),
        sa.Column('lead_time_days', sa.Integer(), nullable=False),
        sa.Column('is_urgent', sa.Boolean(), nullable=False, server_default='false'),
        sa.Column('urgency_reason', sa.Text(), nullable=True),
        sa.Column('waste_risk', sa.String(20), nullable=False, server_default='low'),
        sa.Column('stockout_risk', sa.String(20), nullable=False, server_default='low'),
        sa.Column('supplier_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('safety_stock_calculation', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('shelf_life_adjustment', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('inventory_projection', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=False, server_default=sa.text('now()')),
        sa.PrimaryKeyConstraint('id'),
        sa.ForeignKeyConstraint(['replenishment_plan_id'], ['replenishment_plans.id'], ondelete='CASCADE')
    )
    op.create_index('ix_replenishment_plan_items_plan_id', 'replenishment_plan_items', ['replenishment_plan_id'])
    op.create_index('ix_replenishment_plan_items_ingredient_id', 'replenishment_plan_items', ['ingredient_id'])
    op.create_index('ix_replenishment_plan_items_order_date', 'replenishment_plan_items', ['order_date'])
    op.create_index('ix_replenishment_plan_items_is_urgent', 'replenishment_plan_items', ['is_urgent'])

    # Create inventory_projections table
    op.create_table('inventory_projections',
        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('ingredient_name', sa.String(200), nullable=False),
        sa.Column('projection_date', sa.Date(), nullable=False),
        sa.Column('starting_stock', sa.Numeric(12, 3), nullable=False),
        sa.Column('forecasted_consumption', sa.Numeric(12, 3), nullable=False, server_default='0'),
        sa.Column('scheduled_receipts', sa.Numeric(12, 3), nullable=False, server_default='0'),
        sa.Column('projected_ending_stock', sa.Numeric(12, 3), nullable=False),
        sa.Column('is_stockout', sa.Boolean(), nullable=False, server_default='false'),
        sa.Column('coverage_gap', sa.Numeric(12, 3), nullable=False, server_default='0'),
        sa.Column('replenishment_plan_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=False, server_default=sa.text('now()')),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index('ix_inventory_projections_tenant_id', 'inventory_projections', ['tenant_id'])
    op.create_index('ix_inventory_projections_ingredient_id', 'inventory_projections', ['ingredient_id'])
    op.create_index('ix_inventory_projections_projection_date', 'inventory_projections', ['projection_date'])
    op.create_index('ix_inventory_projections_is_stockout', 'inventory_projections', ['is_stockout'])
    op.create_index('ix_inventory_projections_unique', 'inventory_projections', ['tenant_id', 'ingredient_id', 'projection_date'], unique=True)

    # Create supplier_allocations table
    op.create_table('supplier_allocations',
        sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('replenishment_plan_item_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('requirement_id', postgresql.UUID(as_uuid=True), nullable=True),
        sa.Column('supplier_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('supplier_name', sa.String(200), nullable=False),
        sa.Column('allocation_type', sa.String(20), nullable=False),
        sa.Column('allocated_quantity', sa.Numeric(12, 3), nullable=False),
        sa.Column('allocation_percentage', sa.Numeric(5, 4), nullable=False),
        sa.Column('unit_price', sa.Numeric(12, 2), nullable=False),
        sa.Column('total_cost', sa.Numeric(12, 2), nullable=False),
        sa.Column('lead_time_days', sa.Integer(), nullable=False),
        sa.Column('supplier_score', sa.Numeric(5, 2), nullable=False),
        sa.Column('score_breakdown', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column('allocation_reason', sa.Text(), nullable=True),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=False, server_default=sa.text('now()')),
        sa.PrimaryKeyConstraint('id'),
        sa.ForeignKeyConstraint(['replenishment_plan_item_id'], ['replenishment_plan_items.id'], ondelete='CASCADE')
    )
    op.create_index('ix_supplier_allocations_plan_item_id', 'supplier_allocations', ['replenishment_plan_item_id'])
    op.create_index('ix_supplier_allocations_requirement_id', 'supplier_allocations', ['requirement_id'])
    op.create_index('ix_supplier_allocations_supplier_id', 'supplier_allocations', ['supplier_id'])

    # Create supplier_selection_history table
    op.create_table('supplier_selection_history',
        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('ingredient_name', sa.String(200), nullable=False),
        sa.Column('selected_supplier_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('selected_supplier_name', sa.String(200), nullable=False),
        sa.Column('selection_date', sa.Date(), nullable=False),
        sa.Column('quantity', sa.Numeric(12, 3), nullable=False),
        sa.Column('unit_price', sa.Numeric(12, 2), nullable=False),
        sa.Column('total_cost', sa.Numeric(12, 2), nullable=False),
        sa.Column('lead_time_days', sa.Integer(), nullable=False),
        sa.Column('quality_score', sa.Numeric(5, 2), nullable=True),
        sa.Column('delivery_performance', sa.Numeric(5, 2), nullable=True),
        sa.Column('selection_strategy', sa.String(50), nullable=False),
        sa.Column('was_primary_choice', sa.Boolean(), nullable=False, server_default='true'),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=False, server_default=sa.text('now()')),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index('ix_supplier_selection_history_tenant_id', 'supplier_selection_history', ['tenant_id'])
    op.create_index('ix_supplier_selection_history_ingredient_id', 'supplier_selection_history', ['ingredient_id'])
    op.create_index('ix_supplier_selection_history_supplier_id', 'supplier_selection_history', ['selected_supplier_id'])
    op.create_index('ix_supplier_selection_history_selection_date', 'supplier_selection_history', ['selection_date'])

    # ========================================================================
    # AUDIT LOG TABLE
    # ========================================================================

    # Create audit_logs table
    op.create_table('audit_logs',
        sa.Column('id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('tenant_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('user_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('action', sa.String(length=100), nullable=False),
        sa.Column('resource_type', sa.String(length=100), nullable=False),
        sa.Column('resource_id', sa.String(length=255), nullable=True),
        sa.Column('severity', sa.String(length=20), nullable=False),
        sa.Column('service_name', sa.String(length=100), nullable=False),
        sa.Column('description', sa.Text(), nullable=True),
        sa.Column('changes', postgresql.JSON(astext_type=sa.Text()), nullable=True),
        sa.Column('audit_metadata', postgresql.JSON(astext_type=sa.Text()), nullable=True),
        sa.Column('ip_address', sa.String(length=45), nullable=True),
        sa.Column('user_agent', sa.Text(), nullable=True),
        sa.Column('endpoint', sa.String(length=255), nullable=True),
        sa.Column('method', sa.String(length=10), nullable=True),
        sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
        sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_audit_logs_action'), 'audit_logs', ['action'], unique=False)
    op.create_index(op.f('ix_audit_logs_created_at'), 'audit_logs', ['created_at'], unique=False)
    op.create_index(op.f('ix_audit_logs_resource_id'), 'audit_logs', ['resource_id'], unique=False)
    op.create_index(op.f('ix_audit_logs_resource_type'), 'audit_logs', ['resource_type'], unique=False)
    op.create_index(op.f('ix_audit_logs_service_name'), 'audit_logs', ['service_name'], unique=False)
    op.create_index(op.f('ix_audit_logs_severity'), 'audit_logs', ['severity'], unique=False)
    op.create_index(op.f('ix_audit_logs_tenant_id'), 'audit_logs', ['tenant_id'], unique=False)
    op.create_index(op.f('ix_audit_logs_user_id'), 'audit_logs', ['user_id'], unique=False)
    op.create_index('idx_audit_resource_type_action', 'audit_logs', ['resource_type', 'action'], unique=False)
    op.create_index('idx_audit_service_created', 'audit_logs', ['service_name', 'created_at'], unique=False)
    op.create_index('idx_audit_severity_created', 'audit_logs', ['severity', 'created_at'], unique=False)
    op.create_index('idx_audit_tenant_created', 'audit_logs', ['tenant_id', 'created_at'], unique=False)
    op.create_index('idx_audit_user_created', 'audit_logs', ['user_id', 'created_at'], unique=False)


def downgrade() -> None:
    # Drop tables in reverse order of creation
    op.drop_table('audit_logs')
    op.drop_table('supplier_selection_history')
    op.drop_table('supplier_allocations')
    op.drop_table('inventory_projections')
    op.drop_table('replenishment_plan_items')
    op.drop_table('replenishment_plans')
    op.drop_table('supplier_invoices')
    op.drop_table('delivery_items')
    op.drop_table('deliveries')
    op.drop_table('purchase_order_items')
    op.drop_table('purchase_orders')
    op.drop_table('procurement_requirements')
    op.drop_table('procurement_plans')

    # Drop enum types
    op.execute("DROP TYPE IF EXISTS purchaseorderstatus")
    op.execute("DROP TYPE IF EXISTS deliverystatus")
    op.execute("DROP TYPE IF EXISTS invoicestatus")