-- 007_worker_vip_levels_and_invite.sql —— VIP 等级体系与邀请绑定。
--
-- 说明：
-- 1. 等级升级按累计验收通过（accepted）工单数，阈值存 permission_json.upgradeThreshold，后台可配；
-- 2. 每个打手拥有唯一邀请码，注册时可填邀请码绑定邀请人（inviter_id）；
-- 3. 存量打手统一归 VIP1，原 regular 等级停用；
-- 4. 佣金结算暂缓（规则未定），本迁移只落邀请关系，后续按规则补佣金。

-- 1) worker_users 增加邀请字段
ALTER TABLE worker_users ADD COLUMN IF NOT EXISTS inviter_id BIGINT REFERENCES worker_users(id) ON DELETE SET NULL;
ALTER TABLE worker_users ADD COLUMN IF NOT EXISTS invite_code TEXT;

-- 2) 存量用户填充唯一邀请码（8 位大写字母数字）
UPDATE worker_users
SET invite_code = UPPER(SUBSTRING(MD5(random()::text || id::text) FROM 1 FOR 8))
WHERE invite_code IS NULL;

ALTER TABLE worker_users ALTER COLUMN invite_code SET NOT NULL;
CREATE UNIQUE INDEX IF NOT EXISTS idx_worker_users_invite_code ON worker_users(invite_code);
CREATE INDEX IF NOT EXISTS idx_worker_users_inviter ON worker_users(inviter_id);

-- 3) seed VIP1-5 等级（level_key 唯一，重复执行不覆盖）
INSERT INTO worker_levels (level_key, name, sort_order, status, permission_json, created_at, updated_at) VALUES
  ('vip1', 'VIP1', 10, 'active', '{"depositFreeAmount":0,"maxActiveOrders":1,"upgradeThreshold":0}', NOW(), NOW()),
  ('vip2', 'VIP2', 20, 'active', '{"depositFreeAmount":0,"maxActiveOrders":3,"upgradeThreshold":10}', NOW(), NOW()),
  ('vip3', 'VIP3', 30, 'active', '{"depositFreeAmount":0,"maxActiveOrders":10,"upgradeThreshold":30}', NOW(), NOW()),
  ('vip4', 'VIP4', 40, 'active', '{"depositFreeAmount":0,"maxActiveOrders":50,"upgradeThreshold":50}', NOW(), NOW()),
  ('vip5', 'VIP5', 50, 'active', '{"depositFreeAmount":0,"maxActiveOrders":100,"upgradeThreshold":100}', NOW(), NOW())
ON CONFLICT (level_key) DO NOTHING;

-- 4) 存量打手统一归 VIP1，原 regular 等级停用
UPDATE worker_levels SET status = 'disabled' WHERE level_key = 'regular';
UPDATE worker_users
SET level_id = (SELECT id FROM worker_levels WHERE level_key = 'vip1')
WHERE level_id IS NULL
   OR level_id = (SELECT id FROM worker_levels WHERE level_key = 'regular');

-- 5) 打手等级升级记录
CREATE TABLE IF NOT EXISTS worker_level_logs (
  id BIGSERIAL PRIMARY KEY,
  worker_id BIGINT NOT NULL REFERENCES worker_users(id) ON DELETE CASCADE,
  from_level_id BIGINT REFERENCES worker_levels(id) ON DELETE SET NULL,
  to_level_id BIGINT NOT NULL REFERENCES worker_levels(id) ON DELETE SET NULL,
  reason TEXT NOT NULL DEFAULT 'auto',
  payload_json JSONB NOT NULL DEFAULT '{}'::jsonb,
  created_at TIMESTAMPTZ NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_worker_level_logs_worker_created
  ON worker_level_logs(worker_id, created_at DESC);

COMMENT ON COLUMN worker_users.inviter_id IS '邀请人（注册时通过邀请码绑定）';
COMMENT ON COLUMN worker_users.invite_code IS '本人专属邀请码，注册/邀请他人时使用';
COMMENT ON TABLE worker_level_logs IS '打手等级升级流水';
COMMENT ON COLUMN worker_level_logs.reason IS '升级原因：auto 自动升级 / admin 后台调整';
