-- 打手撤单申请：提交后由客服审核，审核通过才执行撤单与处罚。

ALTER TABLE worker_users
  ADD COLUMN IF NOT EXISTS level_penalty_accepted_count INTEGER NOT NULL DEFAULT 0;

CREATE TABLE IF NOT EXISTS worker_order_cancel_requests (
  id BIGSERIAL PRIMARY KEY,
  work_order_id BIGINT NOT NULL REFERENCES work_orders(id) ON DELETE CASCADE,
  work_order_share_id BIGINT REFERENCES work_order_shares(id) ON DELETE SET NULL,
  worker_id BIGINT NOT NULL REFERENCES worker_users(id) ON DELETE CASCADE,
  reason TEXT NOT NULL DEFAULT '',
  status TEXT NOT NULL DEFAULT 'pending',
  review_note TEXT NOT NULL DEFAULT '',
  reviewed_by TEXT NOT NULL DEFAULT '',
  level_before_id BIGINT REFERENCES worker_levels(id) ON DELETE SET NULL,
  created_at TIMESTAMPTZ NOT NULL,
  reviewed_at TIMESTAMPTZ,
  updated_at TIMESTAMPTZ NOT NULL
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_worker_cancel_requests_pending_target
  ON worker_order_cancel_requests (work_order_id, worker_id, COALESCE(work_order_share_id, 0))
  WHERE status = 'pending';

CREATE INDEX IF NOT EXISTS idx_worker_cancel_requests_worker_created
  ON worker_order_cancel_requests (worker_id, created_at DESC);

CREATE INDEX IF NOT EXISTS idx_worker_cancel_requests_status_created
  ON worker_order_cancel_requests (status, created_at DESC);

COMMENT ON COLUMN worker_users.level_penalty_accepted_count IS '撤单处罚扣减的有效验收次数，不删除真实历史订单';
COMMENT ON TABLE worker_order_cancel_requests IS '打手发起、客服审核的撤单申请';
