import Constants from 'expo-constants';

type ApiOptions = RequestInit & {
  authHeaders?: Record<string, string>;
};

const fallbackApiBaseUrl = 'http://10.0.2.2:8000/api/v1';

export const apiBaseUrl =
  (Constants.expoConfig?.extra?.apiBaseUrl as string | undefined) || fallbackApiBaseUrl;

export async function apiRequest<T>(path: string, options: ApiOptions = {}): Promise<T> {
  const response = await fetch(`${apiBaseUrl}${path}`, {
    ...options,
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      ...options.authHeaders,
      ...options.headers,
    },
  });

  if (!response.ok) {
    const body = await response.text();
    throw new Error(body || `HTTP ${response.status}`);
  }

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