import { api } from "@/lib/api-client";
import type { PaginatedResponse } from "@/types/common";
import type {
  AIPrompt,
  AIPromptCreateInput,
  AIPromptRenderResponse,
  AIPromptSummary,
} from "@/types/ai-prompt";

interface PromptListParams {
  page?: number;
  size?: number;
  search?: string;
}

export const aiPromptService = {
  async listKeys(
    params: PromptListParams = {},
  ): Promise<PaginatedResponse<AIPromptSummary>> {
    const res = await api.get<PaginatedResponse<AIPromptSummary>>(
      "/ai/prompts",
      params,
    );
    const items = res.items ?? res.data ?? [];
    return {
      items,
      total: res.total ?? items.length,
      page: res.page ?? 1,
      size: res.size ?? items.length,
      pages: res.pages ?? 1,
    };
  },

  async listVersions(key: string): Promise<AIPromptSummary[]> {
    const res = await api.get<PaginatedResponse<AIPromptSummary>>(
      `/ai/prompts/${encodeURIComponent(key)}/versions`,
    );
    return res.items ?? res.data ?? [];
  },

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

  async create(input: AIPromptCreateInput): Promise<AIPrompt> {
    return api.post<AIPrompt>("/ai/prompts", input);
  },

  async activate(id: number): Promise<AIPrompt> {
    return api.post<AIPrompt>(`/ai/prompts/${id}/activate`, {});
  },

  async render(
    id: number,
    variables: Record<string, string>,
  ): Promise<AIPromptRenderResponse> {
    return api.post<AIPromptRenderResponse>(`/ai/prompts/${id}/render`, {
      variables,
    });
  },
};
