const BASE = '/api'

function buildAuthHeaders() {
  const token = sessionStorage.getItem('auth_token')
  return token ? { Authorization: `Bearer ${token}` } : {}
}

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

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

  // Auth
  login: (username, password) => request('POST', '/auth/login', { username, password }),
  me: () => request('GET', '/auth/me'),
  listUsers: () => request('GET', '/users'),
  createUser: (username, password, role) => request('POST', '/users', { username, password, role }),
  deleteUser: (username) => request('DELETE', `/users/${encodeURIComponent(username)}`),

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

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

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

  // Schedule
  compileSchedule: (opts) => request('POST', '/schedule/compile', opts),
  getScheduleWeek: (start, version = null) => {
    const params = new URLSearchParams({ start })
    if (version !== null && version !== undefined) {
      params.set('version', String(version))
    }
    return request('GET', `/schedule/week?${params.toString()}`)
  },
  getRerunTests: () => request('GET', '/tests/rerun'),

  exportWindow: async (windowId) => {
    const params = new URLSearchParams({ window_id: windowId })
    const res = await fetch(`${BASE}/schedule/export?${params}`, {
      headers: {
        ...buildAuthHeaders(),
      },
    })
    if (!res.ok) {
      const err = await res.json().catch(() => ({ detail: res.statusText }))
      const error = new Error(err.detail || `HTTP ${res.status}`)
      error.status = res.status
      throw error
    }
    const blob = await res.blob()
    const disposition = res.headers.get('Content-Disposition') ?? ''
    const match = disposition.match(/filename="([^"]+)"/)
    const filename = match ? match[1] : 'tests.zip'
    return { blob, filename }
  },
}

// 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
}
