-- name: CreateMcpToken :one
INSERT INTO mcp_tokens (
  id, token_hash, user_id, name, issuer, scope,
  acp_session_id, expires_at, created_by
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING id, token_hash, user_id, name, issuer, scope,
          acp_session_id, expires_at, last_used_at, revoked_at,
          created_by, created_at;

-- name: GetMcpTokenByHash :one
-- 鉴权用：仅返回属于 enabled 用户的 token，禁用用户的 MCP token 立即失效
-- （与 web session 解析 GetSessionByTokenHash 的 enabled=true 约束一致）。
SELECT t.id, t.token_hash, t.user_id, t.name, t.issuer, t.scope,
       t.acp_session_id, t.expires_at, t.last_used_at, t.revoked_at,
       t.created_by, t.created_at
FROM mcp_tokens t
JOIN users u ON u.id = t.user_id
WHERE t.token_hash = $1
  AND u.enabled = true;

-- name: GetMcpTokenByID :one
SELECT id, token_hash, user_id, name, issuer, scope,
       acp_session_id, expires_at, last_used_at, revoked_at,
       created_by, created_at
FROM mcp_tokens
WHERE id = $1;

-- name: ListMcpTokens :many
-- ListMcpTokens：admin 看全部；普通 user 看自己持有的 admin-issued。
-- callerUserID 为 NULL 表示 admin（不过滤）；非空表示按 (user_id=$1 AND issuer='admin') 过滤。
-- activeOnly=true 时排除已撤销 / 已过期。
SELECT id, token_hash, user_id, name, issuer, scope,
       acp_session_id, expires_at, last_used_at, revoked_at,
       created_by, created_at
FROM mcp_tokens
WHERE
  (sqlc.narg('caller_user_id')::uuid IS NULL
   OR (user_id = sqlc.narg('caller_user_id')::uuid AND issuer = 'admin'))
  AND
  (NOT sqlc.arg('active_only')::boolean
   OR (revoked_at IS NULL AND (expires_at IS NULL OR expires_at > now())))
ORDER BY created_at DESC;

-- name: UpdateMcpTokenLastUsed :exec
UPDATE mcp_tokens
   SET last_used_at = now()
 WHERE id = $1;

-- name: RevokeMcpToken :one
UPDATE mcp_tokens
   SET revoked_at = now()
 WHERE id = $1 AND revoked_at IS NULL
RETURNING id;

-- name: RevokeMcpTokensBySession :many
-- 给定一个 ACP session 的 ID，把所有引用该 session 的 system token 一次性撤销。
-- 返回已撤销的 token id 列表（用于 audit 写入逐条）。
UPDATE mcp_tokens
   SET revoked_at = now()
 WHERE acp_session_id = $1
   AND issuer = 'system'
   AND revoked_at IS NULL
RETURNING id;

-- name: ReapStaleSystemTokens :many
-- 启动期 reaper：所有 system token 中，关联的 acp_sessions 已经是 crashed/exited 的，全部撤销。
-- ACP 自身的 reaper 必须先把 starting/running 残留转为 crashed，本 query 才能命中。
UPDATE mcp_tokens t
   SET revoked_at = now()
  FROM acp_sessions s
 WHERE t.acp_session_id = s.id
   AND t.issuer = 'system'
   AND t.revoked_at IS NULL
   AND s.status IN ('crashed','exited')
RETURNING t.id;

-- name: PurgeMcpTokensExpired :execrows
-- 后台 jobs runner 用：删 expires_at + retention 之前 / revoked_at + retention 之前的 row。
-- 单条 query 用 OR 条件，retention 同一份。
DELETE FROM mcp_tokens
 WHERE (expires_at IS NOT NULL AND expires_at < $1)
    OR (revoked_at IS NOT NULL AND revoked_at < $1);

-- name: DeleteMcpTokenByID :exec
-- 仅供测试用（生产不允许直接物理删；走撤销）。
DELETE FROM mcp_tokens WHERE id = $1;
