import axios from "axios";

const xsrfCookie = "XSRF-TOKEN";
const xsrfHeader = "X-XSRF-TOKEN";

/** Axios instance for Laravel session JSON API (SPA same-origin). */
export const api = axios.create({
  baseURL: "/",
  withCredentials: true,
  withXSRFToken: true,
  xsrfCookieName: xsrfCookie,
  xsrfHeaderName: xsrfHeader,
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
    "X-Requested-With": "XMLHttpRequest",
  },
});

let csrfReady = false;

export async function ensureCsrf() {
  if (csrfReady) {
    return;
  }
  const origin =
    typeof window !== "undefined" ? window.location.origin : "";
  try {
    await axios.get(`${origin}/sanctum/csrf-cookie`, {
      withCredentials: true,
    });
  } catch {
    // SPA without sanctum middleware in tests
  }
  csrfReady = true;
}

export function resetCsrfState() {
  csrfReady = false;
}
