const BASE = '/api'

async function request(method, path, body) {
  const res = await fetch(`${BASE}${path}`, {
    method,
    headers: body !== undefined ? { 'Content-Type': 'application/json' } : {},
    body: body !== undefined ? JSON.stringify(body) : undefined,
  })
  if (!res.ok) {
    const err = await res.json().catch(() => ({ detail: res.statusText }))
    throw new Error(err.detail || `HTTP ${res.status}`)
  }
  return res.json()
}

export const api = {
  // Health
  health: () => request('GET', '/health'),

  // Settings
  getSettings: () => request('GET', '/settings'),
  saveSettings: (settings) => request('POST', '/settings', { settings }),

  // Holidays
  getHolidays: () => request('GET', '/holidays'),
  saveHolidays: (dates) => request('POST', '/holidays', { dates }),

  // Tests
  loadCsv: (csv_path) => request('POST', '/tests/load', { csv_path }),

  // Schedule
  compileSchedule: (opts) => request('POST', '/schedule/compile', opts),
  getScheduleWeek: (start) => request('GET', `/schedule/week?start=${start}`),
  getRerunTests: () => request('GET', '/tests/rerun'),
}

// Transform the flat items array from GET /api/schedule/week into the
// { "YYYY-MM-DD": { shift1: [], shift2: [], shift3: [] } } shape the Calendar expects.
export function groupScheduleItems(items = []) {
  const out = {}
  for (const item of items) {
    const key = item.scheduled_date
    if (!out[key]) out[key] = { shift1: [], shift2: [], shift3: [] }
    const shiftKey = `shift${item.shift_index}`
    out[key][shiftKey].push(item)
  }
  return out
}
