-- 034_worker_product_match_catalog.sql —— 接单模板与快手商品/SKU 映射、匹配日志。

CREATE TABLE IF NOT EXISTS work_product_rule_mappings (
  id BIGSERIAL PRIMARY KEY,
  rule_id BIGINT NOT NULL REFERENCES work_product_rules(id) ON DELETE CASCADE,
  seller_ids_json JSONB NOT NULL DEFAULT '[]'::jsonb,
  rel_item_id TEXT NOT NULL DEFAULT '',
  item_title TEXT NOT NULL DEFAULT '',
  rel_sku_id TEXT NOT NULL DEFAULT '',
  sku_nick TEXT NOT NULL DEFAULT '',
  mapping_type TEXT NOT NULL DEFAULT 'product_default'
    CHECK (mapping_type IN ('product_default', 'sku_exact', 'sku_series')),
  enabled BOOLEAN NOT NULL DEFAULT true,
  created_at TIMESTAMPTZ NOT NULL,
  updated_at TIMESTAMPTZ NOT NULL,
  CHECK (jsonb_typeof(seller_ids_json) = 'array' AND jsonb_array_length(seller_ids_json) > 0),
  CHECK (mapping_type IN ('sku_exact', 'sku_series') OR rel_item_id <> '' OR item_title <> ''),
  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_lookup_idx
  ON work_product_rule_mappings (rel_item_id, mapping_type, enabled);

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

CREATE TABLE IF NOT EXISTS work_product_match_logs (
  id BIGSERIAL PRIMARY KEY,
  order_id BIGINT REFERENCES orders(id) ON DELETE SET NULL,
  order_item_id BIGINT REFERENCES order_items(id) ON DELETE SET NULL,
  source TEXT NOT NULL DEFAULT '',
  seller_id TEXT NOT NULL DEFAULT '',
  rel_item_id TEXT NOT NULL DEFAULT '',
  item_title TEXT NOT NULL DEFAULT '',
  rel_sku_id TEXT NOT NULL DEFAULT '',
  sku_nick TEXT NOT NULL DEFAULT '',
  match_status TEXT NOT NULL CHECK (match_status IN ('matched', 'unmatched', 'ambiguous')),
  rule_id BIGINT REFERENCES work_product_rules(id) ON DELETE SET NULL,
  mapping_id BIGINT REFERENCES work_product_rule_mappings(id) ON DELETE SET NULL,
  candidates_json JSONB NOT NULL DEFAULT '[]'::jsonb,
  raw_payload_json JSONB NOT NULL DEFAULT '{}'::jsonb,
  created_at TIMESTAMPTZ NOT NULL
);

CREATE INDEX IF NOT EXISTS work_product_match_logs_created_idx
  ON work_product_match_logs (created_at DESC, id DESC);

CREATE INDEX IF NOT EXISTS work_product_match_logs_status_idx
  ON work_product_match_logs (match_status, created_at DESC);

COMMENT ON TABLE work_product_rule_mappings IS '快手多店商品、SKU 精确与数量系列到接单模板的确定性映射';
COMMENT ON TABLE work_product_match_logs IS '快手接单商品匹配日志与调试载荷快照';
