-- 029_worker_sessions.sql —— 打手端登录设备会话。

CREATE TABLE IF NOT EXISTS worker_sessions (
  id BIGSERIAL PRIMARY KEY,
  session_id TEXT NOT NULL UNIQUE,
  worker_id BIGINT NOT NULL REFERENCES worker_users(id) ON DELETE CASCADE,
  device_id TEXT NOT NULL DEFAULT '',
  device_type TEXT NOT NULL DEFAULT 'pc',
  device_name TEXT NOT NULL DEFAULT '',
  user_agent TEXT NOT NULL DEFAULT '',
  ip_address TEXT NOT NULL DEFAULT '',
  status TEXT NOT NULL DEFAULT 'active',
  issued_at TIMESTAMPTZ NOT NULL,
  last_seen_at TIMESTAMPTZ NOT NULL,
  expires_at TIMESTAMPTZ NOT NULL,
  revoked_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL,
  updated_at TIMESTAMPTZ NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_worker_sessions_worker_status
  ON worker_sessions(worker_id, status, expires_at DESC);
CREATE INDEX IF NOT EXISTS idx_worker_sessions_worker_device
  ON worker_sessions(worker_id, device_type, device_id, status);

COMMENT ON TABLE worker_sessions IS '打手端登录会话与设备记录';
COMMENT ON COLUMN worker_sessions.device_type IS '设备类型：pc、mobile 等；所有设备合计每个账号最多 3 台';
