CREATE TABLE IF NOT EXISTS worker_sms_codes (
  id BIGSERIAL PRIMARY KEY,
  phone TEXT NOT NULL,
  purpose TEXT NOT NULL DEFAULT 'register',
  code_hash TEXT NOT NULL,
  expires_at TIMESTAMPTZ NOT NULL,
  consumed_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_worker_sms_codes_phone_created
  ON worker_sms_codes(phone, created_at DESC);

UPDATE worker_users wu
SET phone = ''
FROM (
  SELECT MIN(id) AS keep_id, phone
  FROM worker_users
  WHERE phone != ''
  GROUP BY phone
  HAVING COUNT(*) > 1
) dup
WHERE wu.phone = dup.phone AND wu.id <> dup.keep_id;

CREATE UNIQUE INDEX IF NOT EXISTS idx_worker_users_phone
  ON worker_users(phone)
  WHERE phone != '';

COMMENT ON TABLE worker_sms_codes IS '打手注册短信验证码（哈希存储，一次性消费）';
