-- 008_work_order_sharing.sql —— 接单工单拼单能力。
--
-- 说明：
-- 1. 工单可开启拼单：sharing_total_quantity 总数量、sharing_unit_reward 单价（分），
--    打手按单价×数量参与，验收统一通过后按份额结算；
-- 2. 拼单与整单抢单不互斥（未拼满时整单仍可抢走）；
-- 3. 每个打手在同一拼单工单最多一个份额（UNIQUE 约束）。

ALTER TABLE work_orders ADD COLUMN IF NOT EXISTS sharing_enabled BOOLEAN NOT NULL DEFAULT false;
ALTER TABLE work_orders ADD COLUMN IF NOT EXISTS sharing_total_quantity INTEGER NOT NULL DEFAULT 1;
ALTER TABLE work_orders ADD COLUMN IF NOT EXISTS sharing_unit_reward INTEGER NOT NULL DEFAULT 0;

-- 物品规则同样支持拼单配置，自动创建工单时带入
ALTER TABLE work_product_rules ADD COLUMN IF NOT EXISTS sharing_enabled BOOLEAN NOT NULL DEFAULT false;
ALTER TABLE work_product_rules ADD COLUMN IF NOT EXISTS sharing_total_quantity INTEGER NOT NULL DEFAULT 1;
ALTER TABLE work_product_rules ADD COLUMN IF NOT EXISTS sharing_unit_reward INTEGER NOT NULL DEFAULT 0;

CREATE TABLE IF NOT EXISTS work_order_shares (
  id BIGSERIAL PRIMARY KEY,
  work_order_id BIGINT NOT NULL REFERENCES work_orders(id) ON DELETE CASCADE,
  worker_id BIGINT NOT NULL REFERENCES worker_users(id) ON DELETE CASCADE,
  quantity INTEGER NOT NULL DEFAULT 1,
  unit_reward INTEGER NOT NULL DEFAULT 0,
  share_reward INTEGER NOT NULL DEFAULT 0,
  share_deposit INTEGER NOT NULL DEFAULT 0,
  status TEXT NOT NULL DEFAULT 'joined',
  acceptance_json JSONB NOT NULL DEFAULT '{}'::jsonb,
  submitted_at TIMESTAMPTZ,
  accepted_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL,
  updated_at TIMESTAMPTZ NOT NULL,
  UNIQUE (work_order_id, worker_id)
);

CREATE INDEX IF NOT EXISTS idx_work_order_shares_work_order
  ON work_order_shares(work_order_id);
CREATE INDEX IF NOT EXISTS idx_work_order_shares_worker
  ON work_order_shares(worker_id, status, id DESC);

COMMENT ON COLUMN work_orders.sharing_enabled IS '是否启用拼单（多打手按数量参与同一工单）';
COMMENT ON COLUMN work_orders.sharing_total_quantity IS '拼单总数量';
COMMENT ON COLUMN work_orders.sharing_unit_reward IS '拼单单价（分/个），按此结算份额报酬';
COMMENT ON TABLE work_order_shares IS '拼单参与份额：打手参与拼单工单的记录';
COMMENT ON COLUMN work_order_shares.quantity IS '该打手拼单数量';
COMMENT ON COLUMN work_order_shares.unit_reward IS '参与时的拼单单价快照（分）';
COMMENT ON COLUMN work_order_shares.share_reward IS '份额报酬 = quantity × unit_reward（分）';
COMMENT ON COLUMN work_order_shares.share_deposit IS '份额押金（按总量比例分摊，分）';
COMMENT ON COLUMN work_order_shares.status IS 'joined 已参与 / submitted 已提交验收 / accepted 已验收 / cancelled 已取消';
COMMENT ON COLUMN work_order_shares.acceptance_json IS '拼单者各自的验收资料';
