import { getAuthTokenFromSession } from "~/lib/session.server";

const API_BASE_URL = process.env.API_BASE_URL || "http://localhost/api";

interface ApiOptions {
  method?: string;
  body?: Record<string, unknown>;
  token?: string | null;
  request?: Request;
}

/**
 * Server-side API request helper for use in Remix loaders/actions.
 * Talks to the Laravel backend from the server, avoiding client-side fetch.
 *
 * Pass `request` to auto-extract the JWT from the cookie session.
 * Or pass `token` directly if you already have it.
 */
export async function serverApiRequest<T = unknown>(
  endpoint: string,
  options: ApiOptions = {}
): Promise<T> {
  const { method = "GET", body, request } = options;
  const url = `${API_BASE_URL}${endpoint}`;

  let token = options.token ?? null;
  if (!token && request) {
    token = await getAuthTokenFromSession(request);
  }

  const headers: Record<string, string> = {
    Accept: "application/json",
    "Content-Type": "application/json",
  };

  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }

  const fetchOptions: RequestInit = { method, headers };
  if (body && method !== "GET") {
    fetchOptions.body = JSON.stringify(body);
  }

  const response = await fetch(url, fetchOptions);

  if (!response.ok) {
    throw new Response(`API error: ${response.status}`, {
      status: response.status,
    });
  }

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