import defaultCars from './carOptions.json';

const normalizeCars = (cars) =>
  Array.isArray(cars) && cars.length ? cars : defaultCars;

export const loadCars = async () => {
  try {
    const res = await fetch('/api/cars');
    if (!res.ok) throw new Error('Failed to load cars');
    const cars = await res.json();
    return normalizeCars(cars);
  } catch {
    return normalizeCars(defaultCars);
  }
};

export const saveCars = async (cars) => {
  const normalized = normalizeCars(cars);
  try {
    await fetch('/api/cars', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(normalized),
    });
  } catch {
    // silently fail
  }
};

export const addCar = async (car) => {
  const res = await fetch('/api/cars', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(car),
  });
  if (!res.ok) throw new Error('Failed to add car');
  return res.json();
};

export const updateCar = async (id, car) => {
  const res = await fetch(`/api/cars/${id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(car),
  });
  if (!res.ok) throw new Error('Failed to update car');
  return res.json();
};

export const deleteCarById = async (id) => {
  const res = await fetch(`/api/cars/${id}`, {
    method: 'DELETE',
  });
  if (!res.ok) throw new Error('Failed to delete car');
  return res.json();
};

export const verifyPassword = async (password) => {
  const res = await fetch('/api/auth/verify', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ password }),
  });
  if (!res.ok) return false;
  const data = await res.json();
  return data.authenticated;
};
