-- ================================================================
-- Performance Indexes Migration for Inventory Service
-- Created: 2025-11-15
-- Purpose: Add indexes to improve dashboard query performance
-- ================================================================

-- Index for ingredients by tenant and ingredient_category
-- Used in: get_stock_by_category, get_business_model_metrics
CREATE INDEX IF NOT EXISTS idx_ingredients_tenant_ing_category
ON ingredients(tenant_id, ingredient_category)
WHERE is_active = true;

-- Index for ingredients by tenant and product_category
-- Used in: get_stock_status_by_category
CREATE INDEX IF NOT EXISTS idx_ingredients_tenant_prod_category
ON ingredients(tenant_id, product_category)
WHERE is_active = true;

-- Index for stock by tenant, ingredient, and availability
-- Used in: get_stock_summary_by_tenant, get_ingredient_stock_levels
CREATE INDEX IF NOT EXISTS idx_stock_tenant_ingredient_available
ON stock(tenant_id, ingredient_id, is_available);

-- Index for food_safety_alerts by tenant, status, and severity
-- Used in: get_alerts_by_severity, get_food_safety_dashboard
CREATE INDEX IF NOT EXISTS idx_alerts_tenant_status_severity
ON food_safety_alerts(tenant_id, status, severity);

-- Index for stock_movements by tenant and movement_date (descending)
-- Used in: get_movements_by_type, get_recent_activity
CREATE INDEX IF NOT EXISTS idx_movements_tenant_date
ON stock_movements(tenant_id, movement_date DESC);

-- Index for stock by tenant and ingredient with quantity
-- Used in: get_live_metrics with stock level calculations
CREATE INDEX IF NOT EXISTS idx_stock_tenant_quantity
ON stock(tenant_id, ingredient_id, quantity_current)
WHERE is_available = true;

-- Index for ingredients by tenant and creation date
-- Used in: get_recent_activity for recently added ingredients
CREATE INDEX IF NOT EXISTS idx_ingredients_tenant_created
ON ingredients(tenant_id, created_at DESC)
WHERE is_active = true;

-- Composite index for stock movements by type and date
-- Used in: get_movements_by_type with date filtering
CREATE INDEX IF NOT EXISTS idx_movements_type_date
ON stock_movements(tenant_id, movement_type, movement_date DESC);
