import { childLogger } from '@server/logger';
const log = childLogger('ai.client');

export async function callAIEndpoint(endpoint: string, payload: object) {
  try {
    const response = await fetch(endpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });

    const data = await response.json();

    if (!response.ok || data.error) {
      log.error({ error: data.error, details: data.details }, "API route error");
      throw new Error(data.error || `Request failed: ${response.status}`);
    }

    return data;
  } catch (error) {
    log.error({ err: error }, 'API request error');
    throw error;
  }
}
