CREATE TABLE IF NOT EXISTS product_match_rules (
  id BIGSERIAL PRIMARY KEY,
  provider TEXT NOT NULL DEFAULT '',
  platform TEXT NOT NULL DEFAULT '',
  shop_id TEXT NOT NULL DEFAULT '',
  external_item_id TEXT NOT NULL DEFAULT '',
  external_sku_code TEXT NOT NULL DEFAULT '',
  external_sku_name TEXT NOT NULL DEFAULT '',
  external_sku_name_normalized TEXT NOT NULL DEFAULT '',
  resolved_sku_code TEXT NOT NULL,
  enabled BOOLEAN NOT NULL DEFAULT TRUE,
  priority INTEGER NOT NULL DEFAULT 100,
  config_json JSONB NOT NULL DEFAULT '{}'::jsonb,
  created_at TIMESTAMPTZ NOT NULL,
  updated_at TIMESTAMPTZ NOT NULL
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_product_match_rules_unique
  ON product_match_rules(
    provider,
    platform,
    shop_id,
    external_item_id,
    external_sku_code,
    external_sku_name_normalized,
    resolved_sku_code
  );

CREATE INDEX IF NOT EXISTS idx_product_match_rules_lookup
  ON product_match_rules(provider, platform, shop_id, enabled, priority, id);
