/**
 * Lecture des barèmes publiés par l'API REST (vue `public.baremes_publics`), clé publique seulement.
 */
import { lireBareme, type Bareme } from './modele.ts';

export interface ConfigurationApi {
  url: string;
  cle: string;
}

export async function chargerBaremes(
  config: ConfigurationApi,
  options: { fetch?: typeof fetch } = {},
): Promise<Bareme[]> {
  const url = new URL('/rest/v1/baremes_publics?select=*&order=code.asc', config.url);
  const reponse = await (options.fetch ?? fetch)(url, {
    headers: { apikey: config.cle, Accept: 'application/json' },
  });
  if (!reponse.ok) throw new Error(`Lecture des barèmes impossible (HTTP ${reponse.status})`);
  const corps: unknown = await reponse.json();
  if (!Array.isArray(corps)) throw new Error('Réponse inattendue de l’API');
  return (corps as unknown[]).map(lireBareme);
}
