import type { ChemicalInventory, Protocol, SafetyIssue } from '../shared/types';

async function apiFetch(path: string, options: RequestInit = {}): Promise<Response> {
  const res = await fetch(path, {
    ...options,
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ error: res.statusText }));
    throw new Error(err.error || 'API error');
  }
  return res;
}

export const chemicalsApi = {
  list: (): Promise<ChemicalInventory[]> =>
    apiFetch('/api/chemicals').then(r => r.json()),

  create: (data: Partial<ChemicalInventory>): Promise<ChemicalInventory> =>
    apiFetch('/api/chemicals', {
      method: 'POST',
      body: JSON.stringify(data),
    }).then(r => r.json()),

  update: (id: string, data: Partial<ChemicalInventory>): Promise<ChemicalInventory> =>
    apiFetch(`/api/chemicals/${id}`, {
      method: 'PATCH',
      body: JSON.stringify(data),
    }).then(r => r.json()),

  remove: (id: string): Promise<void> =>
    apiFetch(`/api/chemicals/${id}`, { method: 'DELETE' }).then(() => undefined),

  import: (rows: Partial<ChemicalInventory>[]): Promise<{ imported: number; errors: string[] }> =>
    apiFetch('/api/chemicals/import', {
      method: 'POST',
      body: JSON.stringify({ rows }),
    }).then(r => r.json()),
};

export const protocolsApi = {
  list: () => apiFetch('/api/protocols').then(r => r.json()),

  create: (formData: FormData) =>
    fetch('/api/protocols', {
      method: 'POST',
      credentials: 'include',
      body: formData, // Don't set Content-Type — browser sets multipart boundary
    }).then(r => r.json()),

  createFromText: (title: string, content: string) =>
    apiFetch('/api/protocols', {
      method: 'POST',
      body: JSON.stringify({ title, content }),
    }).then(r => r.json()),

  saveAnalysis: (id: string, results: SafetyIssue[]) =>
    apiFetch(`/api/protocols/${id}/analysis`, {
      method: 'PATCH',
      body: JSON.stringify({ analysis_results: results }),
    }).then(r => r.json()),

  analyze: (id: string): Promise<Protocol> =>
    apiFetch(`/api/protocols/${id}/analyze`, {
      method: 'POST',
    }).then(r => r.json()),

  remove: (id: string): Promise<void> =>
    apiFetch(`/api/protocols/${id}`, { method: 'DELETE' }).then(() => undefined),
};
