import axios, { AxiosError, type InternalAxiosRequestConfig } from "axios";

// Kosong ("") = satu domain dengan Laravel: request ke /api relatif (dipakai `npm run build:laravel`).
export const API_URL = (process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000").replace(/\/$/, "");

/**
 * Client API terpusat. Sanctum SPA: cookie sesi dikirim (withCredentials) dan
 * token CSRF dibaca dari cookie XSRF-TOKEN lalu dikirim sebagai header X-XSRF-TOKEN.
 */
export const api = axios.create({
  baseURL: `${API_URL}/api`,
  withCredentials: true,
  withXSRFToken: true,
  headers: {
    Accept: "application/json",
    "X-Requested-With": "XMLHttpRequest",
  },
});

export async function ensureCsrfCookie(): Promise<void> {
  await axios.get(`${API_URL}/sanctum/csrf-cookie`, { withCredentials: true });
}

type RetriableConfig = InternalAxiosRequestConfig & { _csrfRetried?: boolean };

api.interceptors.request.use(async (config) => {
  const method = (config.method ?? "get").toLowerCase();
  const needsCsrf = !["get", "head", "options"].includes(method);
  if (needsCsrf && typeof document !== "undefined" && !document.cookie.includes("XSRF-TOKEN=")) {
    await ensureCsrfCookie();
  }
  return config;
});

api.interceptors.response.use(
  (response) => response,
  async (error: AxiosError) => {
    const status = error.response?.status;
    const config = error.config as RetriableConfig | undefined;

    // 419 = token CSRF kedaluwarsa: ambil ulang lalu coba sekali lagi.
    if (status === 419 && config && !config._csrfRetried) {
      config._csrfRetried = true;
      await ensureCsrfCookie();
      return api.request(config);
    }

    if (status === 401 && typeof window !== "undefined") {
      const path = window.location.pathname;
      const isAuthCall = config?.url === "/login" || config?.url === "/me";
      if (!path.startsWith("/login") && !isAuthCall) {
        const next = encodeURIComponent(path + window.location.search);
        window.location.href = `/login?expired=1&next=${next}`;
      }
    }

    return Promise.reject(error);
  },
);

/** Format error validasi Laravel (422). */
export interface ValidationErrorBody {
  message: string;
  errors?: Record<string, string[]>;
}

export function isAxiosError(err: unknown): err is AxiosError<ValidationErrorBody> {
  return axios.isAxiosError(err);
}

/** Pesan error yang ramah untuk toast. */
export function getErrorMessage(err: unknown, fallback = "Terjadi kesalahan. Silakan coba lagi."): string {
  if (isAxiosError(err)) {
    if (!err.response) return "Tidak dapat terhubung ke server. Periksa koneksi internet Anda.";
    const body = err.response.data;
    if (err.response.status === 422 && body?.errors) {
      const first = Object.values(body.errors)[0]?.[0];
      if (first) return first;
    }
    if (body?.message) return body.message;
    if (err.response.status === 403) return "Anda tidak memiliki akses untuk aksi ini.";
    if (err.response.status >= 500) return "Terjadi kesalahan di server.";
  }
  return fallback;
}

/** Petakan error 422 Laravel ke field react-hook-form. Mengembalikan true jika ada yang dipetakan. */
export function applyServerErrors(
  err: unknown,
  setError: (name: never, error: { type: string; message: string }) => void,
  fields?: readonly string[],
): boolean {
  if (!isAxiosError(err) || err.response?.status !== 422 || !err.response.data?.errors) return false;
  let mapped = false;
  for (const [field, messages] of Object.entries(err.response.data.errors)) {
    if (fields && !fields.includes(field)) continue;
    setError(field as never, { type: "server", message: messages[0] });
    mapped = true;
  }
  return mapped;
}
