export type AcademicPeriod = {
  id: number;
  name: string;
  display_name?: string | null;
  start_date: string; // YYYY-MM-DD
  end_date: string; // YYYY-MM-DD
  period_type: 'schuljahr' | 'semester' | 'trimester';
  is_active: boolean;
};

async function api<T>(url: string, init?: RequestInit): Promise<T> {
  const res = await fetch(url, { credentials: 'include', ...init });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

export async function getAcademicPeriodForDate(date: Date): Promise<AcademicPeriod | null> {
  const iso = date.toISOString().slice(0, 10);
  const { period } = await api<{ period: AcademicPeriod | null }>(
    `/api/academic_periods/for_date?date=${iso}`
  );
  return period ?? null;
}

export async function listAcademicPeriods(): Promise<AcademicPeriod[]> {
  const { periods } = await api<{ periods: AcademicPeriod[] }>(`/api/academic_periods`);
  return Array.isArray(periods) ? periods : [];
}

export async function getActiveAcademicPeriod(): Promise<AcademicPeriod | null> {
  const { period } = await api<{ period: AcademicPeriod | null }>(`/api/academic_periods/active`);
  return period ?? null;
}

export async function setActiveAcademicPeriod(id: number): Promise<AcademicPeriod> {
  const { period } = await api<{ period: AcademicPeriod }>(`/api/academic_periods/active`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ id }),
  });
  return period;
}
