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

const defaults: AppSettings = { // FOR DEBUG AND DEV PURPOSES ONLY ==========================>
  backendUrl: 'http://146.59.230.190:8080',// FOR DEBUG AND DEV PURPOSES ONLY ==========================>
  apiKey:// FOR DEBUG AND DEV PURPOSES ONLY ==========================>
    'b8184608fcab419da2ce9a220ee6017daaff637b627e43ebac31b6b7c3344349',// FOR DEBUG AND DEV PURPOSES ONLY ==========================>
};

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

function joinUrl(
  baseUrl: string,
  path: string,
) {
  return `${baseUrl.replace(/\/+$/, '')}/${path.replace(
    /^\/+/,
    '',
  )}`;
}

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

    const parsed =
      JSON.parse(storedSettings || '{}');

    return {
      ...defaults,
      ...parsed,
      backendUrl:
        parsed.backendUrl?.trim() ||
        defaults.backendUrl,
      apiKey:
        parsed.apiKey?.trim() ||
        defaults.apiKey,
    };
  } catch {
    return defaults;
  }
}

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

export function resetSettings() {
  localStorage.removeItem(SETTINGS_KEY);
}

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

  console.log(
    '[API]',
    joinUrl(settings.backendUrl, path),
  );

  const response = await fetch(
    joinUrl(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>;
}