-- 005_file_storage_and_worker_product_rules.sql —— 统一文件存储与接单物品规则。

CREATE TABLE IF NOT EXISTS file_assets (
  id BIGSERIAL PRIMARY KEY,
  object_key TEXT NOT NULL UNIQUE,
  scene TEXT NOT NULL DEFAULT 'misc',
  original_filename TEXT NOT NULL DEFAULT '',
  content_type TEXT NOT NULL DEFAULT '',
  size_bytes BIGINT NOT NULL DEFAULT 0,
  thumbnail_object_key TEXT NOT NULL DEFAULT '',
  medium_object_key TEXT NOT NULL DEFAULT '',
  url TEXT NOT NULL DEFAULT '',
  thumbnail_url TEXT NOT NULL DEFAULT '',
  medium_url TEXT NOT NULL DEFAULT '',
  uploader_type TEXT NOT NULL DEFAULT '',
  uploader_id TEXT NOT NULL DEFAULT '',
  status TEXT NOT NULL DEFAULT 'active',
  metadata_json JSONB NOT NULL DEFAULT '{}'::jsonb,
  created_at TIMESTAMPTZ NOT NULL,
  updated_at TIMESTAMPTZ NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_file_assets_scene_created
  ON file_assets(scene, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_file_assets_uploader_created
  ON file_assets(uploader_type, uploader_id, created_at DESC);

CREATE TABLE IF NOT EXISTS work_product_rules (
  id BIGSERIAL PRIMARY KEY,
  rule_key TEXT NOT NULL UNIQUE,
  provider TEXT NOT NULL DEFAULT '',
  platform TEXT NOT NULL DEFAULT '',
  shop_id TEXT NOT NULL DEFAULT '',
  sku_code TEXT NOT NULL DEFAULT '',
  product_name TEXT NOT NULL DEFAULT '',
  match_type TEXT NOT NULL DEFAULT 'contains',
  category_id BIGINT REFERENCES work_categories(id) ON DELETE SET NULL,
  enabled BOOLEAN NOT NULL DEFAULT false,
  auto_create BOOLEAN NOT NULL DEFAULT false,
  reward_amount INTEGER NOT NULL DEFAULT 0,
  required_deposit_amount INTEGER NOT NULL DEFAULT 0,
  deposit_threshold_amount INTEGER NOT NULL DEFAULT 20000,
  requirement_json JSONB NOT NULL DEFAULT '{}'::jsonb,
  sort_order INTEGER NOT NULL DEFAULT 100,
  created_at TIMESTAMPTZ NOT NULL,
  updated_at TIMESTAMPTZ NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_work_product_rules_enabled_sort
  ON work_product_rules(enabled, sort_order, id);
CREATE INDEX IF NOT EXISTS idx_work_product_rules_source
  ON work_product_rules(provider, platform, shop_id, sku_code);

CREATE UNIQUE INDEX IF NOT EXISTS idx_work_orders_order_item_unique
  ON work_orders(order_item_id)
  WHERE order_item_id IS NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS idx_work_orders_task_unique
  ON work_orders(task_id)
  WHERE task_id IS NOT NULL;

COMMENT ON TABLE file_assets IS '统一文件资产，底层使用 MinIO/S3 兼容对象存储';
COMMENT ON COLUMN file_assets.object_key IS '对象存储 key';
COMMENT ON COLUMN file_assets.thumbnail_object_key IS '缩略图对象 key';
COMMENT ON COLUMN file_assets.medium_object_key IS '中图对象 key';
COMMENT ON TABLE work_product_rules IS '接单平台物品规则：决定哪些源订单商品生成接单工单';
COMMENT ON COLUMN work_product_rules.reward_amount IS '后台发布给打手的单笔金额，单位分';
COMMENT ON COLUMN work_product_rules.auto_create IS '源订单入库后是否自动创建接单工单';
