import type { Account, Asset, Conversation, Message, ConfigItem } from '@/types';

const BASE = '/api';

async function request<T>(path: string, options?: RequestInit): Promise<T> {
  const res = await fetch(`${BASE}${path}`, {
    headers: { 'Content-Type': 'application/json' },
    ...options,
  });
  if (!res.ok) throw new Error(await res.text());
  return res.json();
}

export const api = {
  // Accounts
  listAccounts: () => request<Account[]>('/accounts'),
  getAccount: (id: string) => request<Account>(`/accounts/${id}`),
  createAccount: (data: Partial<Account>) =>
    request<Account>('/accounts', { method: 'POST', body: JSON.stringify(data) }),
  updateAccount: (id: string, data: Partial<Account>) =>
    request<Account>(`/accounts/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
  deleteAccount: (id: string) =>
    request<void>(`/accounts/${id}`, { method: 'DELETE' }),

  // Prompts
  getPrompt: (accountId: string, type: string) =>
    request<{ path: string; content: string }>(`/prompts/${accountId}/${type}`),
  savePrompt: (accountId: string, type: string, content: string) =>
    request<void>(`/prompts/${accountId}/${type}`, { method: 'PUT', body: JSON.stringify({ content }) }),

  // Conversations
  listConversations: () => request<Conversation[]>('/pipeline/conversations'),
  getMessages: (convId: string) => request<Message[]>(`/pipeline/conversations/${convId}/messages`),

  // Assets
  listAssets: (params?: { accountId?: string; type?: string }) => {
    const qs = new URLSearchParams();
    if (params?.accountId) qs.set('accountId', params.accountId);
    if (params?.type) qs.set('type', params.type);
    return request<Asset[]>(`/assets?${qs}`);
  },
  deleteAsset: (id: string) => request<void>(`/assets/${id}`, { method: 'DELETE' }),

  // Configs
  getConfigs: () => request<ConfigItem[]>('/configs'),
  saveConfig: (key: string, value: Record<string, unknown>) =>
    request<void>(`/configs/${key}`, { method: 'PUT', body: JSON.stringify({ value }) }),
};
