export interface KBEntry {
  id: string;
  restaurantId: string;
  branchId?: string;
  type: string;
  title: string;
  content?: string;
  url?: string;
  question?: string;
  answer?: string;
  status: string;
  embedding_status?: string;
  tags?: string[];
  is_active?: boolean;
  file_size?: string;
  file_type?: string;
  pages?: number;
  created_at?: string;
  createdAt?: string;
  updated_at?: string;
  updatedAt?: string;
}

export interface KBListResponse {
  entries: KBEntry[];
  total: number;
  page: number;
  limit: number;
  pages: number;
}

async function apiFetch<T>(url: string, options?: RequestInit): Promise<T> {
  const res = await fetch(url, { credentials: 'include', ...options });
  const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;
  if (!res.ok) throw new Error((json.error as string) || `Request failed: ${res.status}`);
  return json as T;
}

export async function listKBEntries(params: Record<string, string> = {}): Promise<KBListResponse> {
  const qs = new URLSearchParams(params).toString();
  return apiFetch<KBListResponse>(`/api/knowledge-base${qs ? '?' + qs : ''}`);
}

export async function getKBEntry(id: string): Promise<{ entry: KBEntry }> {
  return apiFetch<{ entry: KBEntry }>(`/api/knowledge-base/${id}`);
}

export async function createKBEntry(body: Record<string, unknown>): Promise<{ entry: KBEntry }> {
  return apiFetch<{ entry: KBEntry }>('/api/knowledge-base', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
}

export async function updateKBEntry(id: string, body: Record<string, unknown>): Promise<{ entry: KBEntry }> {
  return apiFetch<{ entry: KBEntry }>(`/api/knowledge-base/${id}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
}

export async function deleteKBEntry(id: string): Promise<{ success: boolean }> {
  return apiFetch<{ success: boolean }>(`/api/knowledge-base/${id}`, { method: 'DELETE' });
}

export async function reEmbedAll(): Promise<{ success: boolean; queued: number }> {
  return apiFetch<{ success: boolean; queued: number }>('/api/knowledge-base/re-embed', {
    method: 'POST',
  });
}

export async function uploadKBDocument(file: File, branchId?: string): Promise<{ entry: KBEntry }> {
  const formData = new FormData();
  formData.append('file', file);
  if (branchId) formData.append('branch_id', branchId);
  const res = await fetch('/api/knowledge-base/upload', {
    method: 'POST',
    credentials: 'include',
    body: formData,
  });
  const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;
  if (!res.ok) throw new Error((json.error as string) || `Upload failed: ${res.status}`);
  return json as { entry: KBEntry };
}

export async function crawlKBUrl(id: string, url: string): Promise<{ entry: KBEntry; contentLength: number }> {
  return apiFetch<{ entry: KBEntry; contentLength: number }>('/api/knowledge-base/crawl', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ id, url }),
  });
}
