// Code generated by sqlc. DO NOT EDIT.
// versions:
//   sqlc v1.31.1
// source: mcp_tokens.sql

package mcpsqlc

import (
	"context"

	"github.com/jackc/pgx/v5/pgtype"
)

const createMcpToken = `-- 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
`

type CreateMcpTokenParams struct {
	ID           pgtype.UUID        `json:"id"`
	TokenHash    []byte             `json:"token_hash"`
	UserID       pgtype.UUID        `json:"user_id"`
	Name         string             `json:"name"`
	Issuer       string             `json:"issuer"`
	Scope        []byte             `json:"scope"`
	AcpSessionID pgtype.UUID        `json:"acp_session_id"`
	ExpiresAt    pgtype.Timestamptz `json:"expires_at"`
	CreatedBy    pgtype.UUID        `json:"created_by"`
}

func (q *Queries) CreateMcpToken(ctx context.Context, arg CreateMcpTokenParams) (McpToken, error) {
	row := q.db.QueryRow(ctx, createMcpToken,
		arg.ID,
		arg.TokenHash,
		arg.UserID,
		arg.Name,
		arg.Issuer,
		arg.Scope,
		arg.AcpSessionID,
		arg.ExpiresAt,
		arg.CreatedBy,
	)
	var i McpToken
	err := row.Scan(
		&i.ID,
		&i.TokenHash,
		&i.UserID,
		&i.Name,
		&i.Issuer,
		&i.Scope,
		&i.AcpSessionID,
		&i.ExpiresAt,
		&i.LastUsedAt,
		&i.RevokedAt,
		&i.CreatedBy,
		&i.CreatedAt,
	)
	return i, err
}

const deleteMcpTokenByID = `-- name: DeleteMcpTokenByID :exec
DELETE FROM mcp_tokens WHERE id = $1
`

// 仅供测试用（生产不允许直接物理删；走撤销）。
func (q *Queries) DeleteMcpTokenByID(ctx context.Context, id pgtype.UUID) error {
	_, err := q.db.Exec(ctx, deleteMcpTokenByID, id)
	return err
}

const getMcpTokenByHash = `-- name: GetMcpTokenByHash :one
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
`

// 鉴权用：仅返回属于 enabled 用户的 token，禁用用户的 MCP token 立即失效
// （与 web session 解析 GetSessionByTokenHash 的 enabled=true 约束一致）。
func (q *Queries) GetMcpTokenByHash(ctx context.Context, tokenHash []byte) (McpToken, error) {
	row := q.db.QueryRow(ctx, getMcpTokenByHash, tokenHash)
	var i McpToken
	err := row.Scan(
		&i.ID,
		&i.TokenHash,
		&i.UserID,
		&i.Name,
		&i.Issuer,
		&i.Scope,
		&i.AcpSessionID,
		&i.ExpiresAt,
		&i.LastUsedAt,
		&i.RevokedAt,
		&i.CreatedBy,
		&i.CreatedAt,
	)
	return i, err
}

const getMcpTokenByID = `-- 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
`

func (q *Queries) GetMcpTokenByID(ctx context.Context, id pgtype.UUID) (McpToken, error) {
	row := q.db.QueryRow(ctx, getMcpTokenByID, id)
	var i McpToken
	err := row.Scan(
		&i.ID,
		&i.TokenHash,
		&i.UserID,
		&i.Name,
		&i.Issuer,
		&i.Scope,
		&i.AcpSessionID,
		&i.ExpiresAt,
		&i.LastUsedAt,
		&i.RevokedAt,
		&i.CreatedBy,
		&i.CreatedAt,
	)
	return i, err
}

const listMcpTokens = `-- name: ListMcpTokens :many
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
  ($1::uuid IS NULL
   OR (user_id = $1::uuid AND issuer = 'admin'))
  AND
  (NOT $2::boolean
   OR (revoked_at IS NULL AND (expires_at IS NULL OR expires_at > now())))
ORDER BY created_at DESC
`

type ListMcpTokensParams struct {
	CallerUserID pgtype.UUID `json:"caller_user_id"`
	ActiveOnly   bool        `json:"active_only"`
}

// ListMcpTokens：admin 看全部；普通 user 看自己持有的 admin-issued。
// callerUserID 为 NULL 表示 admin（不过滤）；非空表示按 (user_id=$1 AND issuer='admin') 过滤。
// activeOnly=true 时排除已撤销 / 已过期。
func (q *Queries) ListMcpTokens(ctx context.Context, arg ListMcpTokensParams) ([]McpToken, error) {
	rows, err := q.db.Query(ctx, listMcpTokens, arg.CallerUserID, arg.ActiveOnly)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []McpToken
	for rows.Next() {
		var i McpToken
		if err := rows.Scan(
			&i.ID,
			&i.TokenHash,
			&i.UserID,
			&i.Name,
			&i.Issuer,
			&i.Scope,
			&i.AcpSessionID,
			&i.ExpiresAt,
			&i.LastUsedAt,
			&i.RevokedAt,
			&i.CreatedBy,
			&i.CreatedAt,
		); err != nil {
			return nil, err
		}
		items = append(items, i)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

const purgeMcpTokensExpired = `-- name: PurgeMcpTokensExpired :execrows
DELETE FROM mcp_tokens
 WHERE (expires_at IS NOT NULL AND expires_at < $1)
    OR (revoked_at IS NOT NULL AND revoked_at < $1)
`

// 后台 jobs runner 用：删 expires_at + retention 之前 / revoked_at + retention 之前的 row。
// 单条 query 用 OR 条件，retention 同一份。
func (q *Queries) PurgeMcpTokensExpired(ctx context.Context, expiresAt pgtype.Timestamptz) (int64, error) {
	result, err := q.db.Exec(ctx, purgeMcpTokensExpired, expiresAt)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected(), nil
}

const reapStaleSystemTokens = `-- name: ReapStaleSystemTokens :many
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
`

// 启动期 reaper：所有 system token 中，关联的 acp_sessions 已经是 crashed/exited 的，全部撤销。
// ACP 自身的 reaper 必须先把 starting/running 残留转为 crashed，本 query 才能命中。
func (q *Queries) ReapStaleSystemTokens(ctx context.Context) ([]pgtype.UUID, error) {
	rows, err := q.db.Query(ctx, reapStaleSystemTokens)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []pgtype.UUID
	for rows.Next() {
		var id pgtype.UUID
		if err := rows.Scan(&id); err != nil {
			return nil, err
		}
		items = append(items, id)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

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

func (q *Queries) RevokeMcpToken(ctx context.Context, id pgtype.UUID) (pgtype.UUID, error) {
	row := q.db.QueryRow(ctx, revokeMcpToken, id)
	var id_2 pgtype.UUID
	err := row.Scan(&id_2)
	return id_2, err
}

const revokeMcpTokensBySession = `-- name: RevokeMcpTokensBySession :many
UPDATE mcp_tokens
   SET revoked_at = now()
 WHERE acp_session_id = $1
   AND issuer = 'system'
   AND revoked_at IS NULL
RETURNING id
`

// 给定一个 ACP session 的 ID，把所有引用该 session 的 system token 一次性撤销。
// 返回已撤销的 token id 列表（用于 audit 写入逐条）。
func (q *Queries) RevokeMcpTokensBySession(ctx context.Context, acpSessionID pgtype.UUID) ([]pgtype.UUID, error) {
	rows, err := q.db.Query(ctx, revokeMcpTokensBySession, acpSessionID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var items []pgtype.UUID
	for rows.Next() {
		var id pgtype.UUID
		if err := rows.Scan(&id); err != nil {
			return nil, err
		}
		items = append(items, id)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return items, nil
}

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

func (q *Queries) UpdateMcpTokenLastUsed(ctx context.Context, id pgtype.UUID) error {
	_, err := q.db.Exec(ctx, updateMcpTokenLastUsed, id)
	return err
}
