import type { SendResponse, StartResponse } from './chatbot-types';

export class ChatbotClientError extends Error {
  constructor(message: string, readonly statusCode: number) {
    super(message);
    this.name = 'ChatbotClientError';
  }
}

async function handle<T>(res: Response): Promise<T> {
  if (res.status === 204) return undefined as T;
  const data = (await res.json().catch(() => null)) as
    | T
    | { message: string | string[] }
    | null;
  if (!res.ok) {
    const msg =
      (data as { message?: string | string[] } | null)?.message ??
      `Request failed (${res.status})`;
    throw new ChatbotClientError(Array.isArray(msg) ? msg.join('\n') : msg, res.status);
  }
  return data as T;
}

export const chatbotClient = {
  async start(locale: 'en' | 'ur' = 'en'): Promise<StartResponse> {
    const res = await fetch('/api/ai/triage/conversations', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ locale }),
    });
    return handle<StartResponse>(res);
  },
  async send(conversationId: string, content: string): Promise<SendResponse> {
    const res = await fetch('/api/ai/triage/messages', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ conversationId, content }),
    });
    return handle<SendResponse>(res);
  },
};
