-- 037_repair_worker_product_mapping_schema.sql —— 修复旧版商品映射表到多店映射结构。

ALTER TABLE work_product_rule_mappings
  ADD COLUMN IF NOT EXISTS seller_ids_json JSONB;

DO $$
BEGIN
  IF EXISTS (
    SELECT 1
    FROM information_schema.columns
    WHERE table_schema = current_schema()
      AND table_name = 'work_product_rule_mappings'
      AND column_name = 'seller_id'
  ) THEN
    UPDATE work_product_rule_mappings
    SET seller_ids_json = jsonb_build_array(seller_id)
    WHERE seller_ids_json IS NULL
      AND seller_id IS NOT NULL
      AND seller_id <> '';
  END IF;
END
$$;

ALTER TABLE work_product_rule_mappings
  ALTER COLUMN seller_ids_json SET DEFAULT '[]'::jsonb,
  ALTER COLUMN seller_ids_json SET NOT NULL;

DO $$
BEGIN
  IF EXISTS (
    SELECT 1
    FROM information_schema.columns
    WHERE table_schema = current_schema()
      AND table_name = 'work_product_rule_mappings'
      AND column_name = 'seller_id'
  ) THEN
    ALTER TABLE work_product_rule_mappings
      ALTER COLUMN seller_id SET DEFAULT '';
  END IF;
END
$$;

UPDATE work_product_rule_mappings
SET mapping_type = 'sku_exact'
WHERE mapping_type = 'sku_override';

DROP INDEX IF EXISTS work_product_rule_mappings_product_identity_unique;
DROP INDEX IF EXISTS work_product_rule_mappings_sku_identity_unique;

ALTER TABLE work_product_rule_mappings
  DROP CONSTRAINT IF EXISTS work_product_rule_mappings_check,
  DROP CONSTRAINT IF EXISTS work_product_rule_mappings_check1,
  DROP CONSTRAINT IF EXISTS work_product_rule_mappings_mapping_type_check,
  DROP CONSTRAINT IF EXISTS work_product_rule_mappings_seller_id_check,
  DROP CONSTRAINT IF EXISTS work_product_rule_mappings_seller_ids_json_check,
  DROP CONSTRAINT IF EXISTS work_product_rule_mappings_product_scope_check,
  DROP CONSTRAINT IF EXISTS work_product_rule_mappings_sku_scope_check,
  ADD CONSTRAINT work_product_rule_mappings_seller_ids_json_check
    CHECK (jsonb_typeof(seller_ids_json) = 'array' AND jsonb_array_length(seller_ids_json) > 0),
  ADD CONSTRAINT work_product_rule_mappings_mapping_type_check
    CHECK (mapping_type IN ('product_default', 'sku_exact', 'sku_series')),
  ADD CONSTRAINT work_product_rule_mappings_product_scope_check
    CHECK (mapping_type IN ('sku_exact', 'sku_series') OR rel_item_id <> '' OR item_title <> ''),
  ADD CONSTRAINT work_product_rule_mappings_sku_scope_check
    CHECK (
      (mapping_type = 'product_default' AND rel_sku_id = '' AND sku_nick = '')
      OR
      (mapping_type = 'sku_exact' AND (rel_sku_id <> '' OR sku_nick <> ''))
      OR
      (mapping_type = 'sku_series' AND rel_sku_id = '' AND sku_nick <> '')
    );

CREATE INDEX IF NOT EXISTS work_product_rule_mappings_seller_ids_idx
  ON work_product_rule_mappings USING GIN (seller_ids_json);

DROP INDEX IF EXISTS work_product_rule_mappings_lookup_idx;

CREATE INDEX work_product_rule_mappings_lookup_idx
  ON work_product_rule_mappings (rel_item_id, mapping_type, enabled);
