import { api } from "@/lib/api-client";
import type {
  AIAgent,
  AIAgentSummary,
  AIAgentTestRequest,
  AIAgentTestResponse,
  AIAgentUpdateInput,
  AIToolSummary,
} from "@/types/aiAgent";

/**
 * REST helpers for the AI Agent configurator.
 *
 * Backend: `backend/custom_addons/encoach_ai/controllers/agents_controller.py`.
 * Mount point: `/api/ai/agents`.
 */
export const aiAgentService = {
  async list(params?: { search?: string }): Promise<AIAgentSummary[]> {
    const res = await api.get<{ items?: AIAgentSummary[]; data?: AIAgentSummary[] }>(
      "/ai/agents",
      params,
    );
    return res.items ?? res.data ?? [];
  },

  async get(id: number): Promise<AIAgent> {
    return api.get<AIAgent>(`/ai/agents/${id}`);
  },

  async update(id: number, input: AIAgentUpdateInput): Promise<AIAgent> {
    return api.patch<AIAgent>(`/ai/agents/${id}`, input);
  },

  async test(id: number, body: AIAgentTestRequest): Promise<AIAgentTestResponse> {
    return api.post<AIAgentTestResponse>(`/ai/agents/${id}/test`, body);
  },

  async listTools(): Promise<AIToolSummary[]> {
    const res = await api.get<{ items?: AIToolSummary[]; data?: AIToolSummary[] }>(
      "/ai/agents/tools",
    );
    return res.items ?? res.data ?? [];
  },

  async updateTool(
    id: number,
    input: Partial<Pick<AIToolSummary, "active" | "name" | "description">> & {
      schema?: Record<string, unknown>;
    },
  ): Promise<AIToolSummary> {
    return api.patch<AIToolSummary>(`/ai/agents/tools/${id}`, input);
  },
};
