// Centralized fetch wrapper that attaches the auth token from localStorage
// and bounces the user to /login on a 401.
//
// Drop-in for `fetch`: same call signature, same return shape. The only
// differences from raw fetch:
//   1. If a token exists in localStorage and the caller hasn't already set an
//      Authorization header, we attach `Authorization: Bearer ${token}`.
//   2. If the response is 401 *and* we had a token to begin with, we fire an
//      `auth:logout` window event so AuthContext can clear state and redirect
//      to /login. (No token + 401 just returns normally — login pages need
//      that path.)
//
// We intentionally do NOT set Content-Type. FormData uploads rely on fetch
// auto-generating the multipart boundary, and JSON callers set their own
// header. This wrapper only touches Authorization.

export async function apiFetch(
  input: RequestInfo | URL,
  init: RequestInit = {},
): Promise<Response> {
  const token = localStorage.getItem('token');
  const headers = new Headers(init.headers);

  if (token && !headers.has('Authorization')) {
    headers.set('Authorization', `Bearer ${token}`);
  }

  const res = await fetch(input, { ...init, headers });

  if (res.status === 401 && token) {
    window.dispatchEvent(new Event('auth:logout'));
  }

  return res;
}
