import { getDefaultStore } from 'jotai';
import { authAtom } from '../store/authAtom';

// ---------------------------------------------------------------------------
// Platform-agnostic configuration — call configureApiBase and
// configureTokenStorage once at app startup before using any hook.
// ---------------------------------------------------------------------------

let API_BASE = 'http://localhost:3000/api';

/** Inject the API base URL (EXPO_PUBLIC_API_URL on mobile, VITE_API_URL on web) */
export function configureApiBase(url: string): void {
  API_BASE = url;
}

/** Returns the currently configured API base URL */
export function getApiBase(): string {
  return API_BASE;
}

type TokenOps = {
  save: (token: string) => Promise<void>;
  get: () => Promise<string | null>;
  remove: () => Promise<void>;
};

let tokenOps: TokenOps = {
  save: async () => {},
  get: async () => null,
  remove: async () => {},
};

/** Inject the token storage implementation (SecureStore on mobile, localStorage on web) */
export function configureTokenStorage(ops: TokenOps): void {
  tokenOps = ops;
}

export const saveToken = (token: string): Promise<void> => tokenOps.save(token);
export const getToken = (): Promise<string | null> => tokenOps.get();
export const removeToken = (): Promise<void> => tokenOps.remove();

// ---------------------------------------------------------------------------
// Fetch wrapper
// ---------------------------------------------------------------------------

/**
 * Centralized fetch wrapper for all API calls.
 * - Automatically adds Authorization: Bearer header from the configured token storage
 * - Sets Content-Type: application/json when a body is present
 * - On 401: clears the stored token and resets the auth atom (auto-logout)
 */
export async function apiFetch(path: string, options: RequestInit = {}): Promise<Response> {
  const token = await getToken();

  const headers: Record<string, string> = {
    ...(options.headers as Record<string, string>),
  };

  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }

  if (options.body && !headers['Content-Type']) {
    headers['Content-Type'] = 'application/json';
  }

  const response = await fetch(`${API_BASE}${path}`, { ...options, headers });

  // Auto-logout on invalid or expired token
  if (response.status === 401) {
    await removeToken();
    getDefaultStore().set(authAtom, null);
  }

  return response;
}
