// lib/masters-api.ts
import type { Master, MastersQuery } from "./types";

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL ?? "https://api.quantcareers.fr";

/**
 * GET /masters/ — classement trié par score décroissant.
 * Endpoint public (pas de token requis).
 */
export async function getMasters(query: MastersQuery = {}): Promise<Master[]> {
  const params = new URLSearchParams();
  if (query.country) params.set("country", query.country);
  if (query.language) params.set("language", query.language);
  if (query.search) params.set("search", query.search);

  const qs = params.toString();
  const res = await fetch(`${API_BASE_URL}/masters/${qs ? `?${qs}` : ""}`, {
    next: { revalidate: 3600 },
  });

  if (!res.ok) {
    throw new Error(`Impossible de charger le classement (HTTP ${res.status})`);
  }

  return res.json();
}

export async function getAvailableCountries(): Promise<string[]> {
  const all = await getMasters();
  return Array.from(new Set(all.map((m) => m.country))).sort((a, b) =>
    a.localeCompare(b, "fr")
  );
}

export const AVAILABLE_LANGUAGES = ["Français", "Anglais"] as const;
