import type { AppConfig } from '../types';

const config: AppConfig = (window as any).__PAPO__ || {};

export function apiUrl(path: string) {
  const base = config.baseApi || '/api';
  return `${base}${path}`;
}

export async function apiFetch<T>(path: string, init?: RequestInit): Promise<T> {
  const response = await fetch(apiUrl(path), {
    ...init,
    headers: {
      'Content-Type': 'application/json',
      ...(init?.headers || {})
    }
  });

  if (response.status === 401) {
    window.location.href = `${config.baseAuth || '/auth'}/discord`;
    throw new Error('unauthorized');
  }

  if (!response.ok) {
    throw new Error(`request failed: ${response.status}`);
  }

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