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;
}

/** Human-readable message from a failed Laravel JSON API response (422 / 403 / 500). */
export function apiErrorDetail(error) {
  const res = error?.response;
  const data = res?.data;
  if (!data) {
    return typeof error?.message === "string" && error.message.length > 0
      ? error.message
      : "Request failed.";
  }
  if (typeof data === "string") {
    return data;
  }
  if (typeof data.message === "string" && data.message.length > 0) {
    return data.message;
  }
  if (data.errors && typeof data.errors === "object") {
    const parts = [];
    for (const v of Object.values(data.errors)) {
      if (Array.isArray(v)) {
        parts.push(...v.map(String));
      } else if (v != null) {
        parts.push(String(v));
      }
    }
    if (parts.length > 0) {
      return parts.join(" ");
    }
  }
  return `HTTP ${res.status}`;
}
