-- unitSaleRule and unitSaleRuleLabel already exist in 0001_baseline.
-- This migration only adds performance indexes (idempotent via stored procedure).

DROP PROCEDURE IF EXISTS `_migrate_0002`;
CREATE PROCEDURE `_migrate_0002`()
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'sales' AND INDEX_NAME = 'idx_sale_vendor'
  ) THEN
    CREATE INDEX `idx_sale_vendor` ON `sales`(`vendorId`);
  END IF;

  IF NOT EXISTS (
    SELECT 1 FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'sales' AND INDEX_NAME = 'idx_sale_created'
  ) THEN
    CREATE INDEX `idx_sale_created` ON `sales`(`createdAt`);
  END IF;

  IF NOT EXISTS (
    SELECT 1 FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'sales' AND INDEX_NAME = 'idx_sale_product'
  ) THEN
    CREATE INDEX `idx_sale_product` ON `sales`(`productId`);
  END IF;
END;

CALL `_migrate_0002`();
DROP PROCEDURE IF EXISTS `_migrate_0002`;
