package tools

import (
	"context"
	"net/http"

	"security-center-mcp/internal/client"
)

// This file defines whoami: the identity introspection tool. Like
// upload_vulnerability_attachment (vuln_upload.go) it is not an
// EndpointRef mapping executed by callEndpoint — it is a fixed, no-arg
// GET against GET /api/v1/agent/whoami with the backend's data passed
// through verbatim. Dispatch lives in call.go's Dispatch (the tool is
// neither CAASM nor vuln, so it is routed before both families).
//
// The whoami endpoint is deliberately absent from the embedded swagger
// snapshot (that document only covers the caasm/vuln open surface), so
// the Endpoints entry below records the contract path for documentation
// and is exempted from the registry-level swagger conformance checks
// (see swaggerExemptPaths in registry_test.go); its contract is pinned
// by the backend handler tests instead.

// whoamiPath is the backend identity endpoint backing the whoami tool.
const whoamiPath = "/api/v1/agent/whoami"

func whoamiTool() Tool {
	return Tool{
		Name: "whoami",
		Description: "解析当前调用方身份（“我是谁”）。当用户请求涉及“我/我的”——如“我提交的漏洞”“指派给我的漏洞”“我这个 Key 有什么权限”——" +
			"必须先调本工具拿到 user_id / employee_id / permission_scope，再调 search_vulnerabilities 等工具过滤，不要猜测或向用户反问 ID。" +
			"返回字段：actor_type（agent=API Key 调用 / user=人类 JWT）；user_id（用户 ID，agent 时为 Key 主人）——" +
			"“我提交的”用 search_vulnerabilities 的 submitter_user_id=user_id 过滤；employee_id（关联员工 ID，未关联为 null）——" +
			"“指派给我的/修给我的（owner/fixer）”用 owner_employee_id=employee_id 过滤，为 null 时说明账号未关联员工、无法按此维度过滤，应如实告知用户；" +
			"name、email（用户资料）；agent 调用额外返回 agent_id、agent_name 与 permission_scope（本 Key 的权限范围，用于回答“我的 Key 能做什么”）。无参数。",
		InputSchema: objectSchema(nil),
		// 固定单端点、无参数映射（ParamMap/BodyMap 均为空）；Endpoints
		// 仅登记契约路径，swagger 校验豁免见 registry_test.go。
		Endpoints: []EndpointRef{
			{Method: "get", Path: whoamiPath},
		},
	}
}

// callWhoami issues GET /api/v1/agent/whoami and passes the envelope's
// data through verbatim (same convention as callEndpoint). Backend
// business errors and transport failures become the structured
// {"error": ...} payload via errorResult; the tool takes no arguments,
// so *ArgError cannot occur.
func callWhoami(ctx context.Context, c *client.Client) (any, error) {
	var data any
	if err := c.Do(ctx, http.MethodGet, whoamiPath, nil, nil, &data); err != nil {
		return errorResult(err), nil
	}
	return data, nil
}
