import type { AppSettings } from '@/types/api';

const defaults: AppSettings = {
  backendUrl: 'http://localhost:8080',
  apiKey: 'dev-api-key',
};

const SETTINGS_KEY =
  'lr-openwrt-tool.settings';

export function getSettings(): AppSettings {
  try {
    const storedSettings =
      localStorage.getItem(SETTINGS_KEY);

    return {
      ...defaults,
      ...JSON.parse(storedSettings || '{}'),
    };
  } catch {
    return defaults;
  }
}

export function saveSettings(
  settings: AppSettings,
) {
  localStorage.setItem(
    SETTINGS_KEY,
    JSON.stringify(settings),
  );
}

export async function apiRequest<T>(
  path: string,
  init: RequestInit = {},
): Promise<T> {
  const settings = getSettings();

  const response = await fetch(
    `${settings.backendUrl}${path}`,
    {
      ...init,
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': settings.apiKey,
        ...(init.headers || {}),
      },
    },
  );

  if (!response.ok) {
    throw new Error(
      `${response.status} ${response.statusText}`,
    );
  }

  return response.json() as Promise<T>;
}