-- 数据库可观测性与高频查询索引保护。
-- PostgreSQL 容器通过 shared_preload_libraries 预加载；托管数据库若无权限，跳过扩展创建并由平台侧开启。
DO $$
BEGIN
  CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
EXCEPTION
  WHEN insufficient_privilege OR undefined_file THEN
    RAISE NOTICE '无法创建 pg_stat_statements，请在数据库平台侧启用该扩展';
END
$$;

-- 打手订单状态计算中的 pending 撤单/反馈 EXISTS。
CREATE INDEX IF NOT EXISTS idx_worker_cancel_requests_pending_worker_order
  ON worker_order_cancel_requests(worker_id, work_order_id)
  WHERE status = 'pending';

CREATE INDEX IF NOT EXISTS idx_worker_feedbacks_pending_worker_order
  ON worker_order_feedbacks(worker_id, work_order_id)
  WHERE status = 'pending';

-- 工单公共详情和资料更新角标按工单、事件类型取最新事件。
CREATE INDEX IF NOT EXISTS idx_work_order_events_order_type_id
  ON work_order_events(work_order_id, event_type, id DESC);

-- 排行榜按打手和验收时间筛选；全部周期仍需汇总表或缓存，索引不能替代聚合。
CREATE INDEX IF NOT EXISTS idx_work_orders_accepted_worker_at
  ON work_orders(assigned_worker_id, accepted_at DESC)
  WHERE status = 'accepted' AND assigned_worker_id IS NOT NULL;

CREATE INDEX IF NOT EXISTS idx_work_order_shares_accepted_worker_at
  ON work_order_shares(worker_id, accepted_at DESC)
  WHERE status = 'accepted';
