export default defineNuxtPlugin(() => {
  const config = useRuntimeConfig();
  const baseURL = `${config.public.apiBase}${config.public.contextPath}`;

  const api = $fetch.create({
    baseURL,
    credentials: "include",
    onRequest({ request, options }) {
      // 1) GET/HEAD가 아니면 body만 넣기 (GET에 body 금지)
      const method = (options.method ?? "GET").toUpperCase();
      if (method === "GET" || method === "HEAD") {
        delete (options as any).body;
      }

      // 2) FormData면 Content-Type 자동 지정 금지
      const isFormData =
        typeof FormData !== "undefined" && options.body instanceof FormData;
      options.headers = {
        ...(isFormData ? {} : { "Content-Type": "application/json" }),
        ...(options.headers || {}),
      };

      // 3) SSR 쿠키 포워딩
      if (import.meta.server) {
        const cookie = useRequestHeaders(["cookie"])?.cookie;
        const reqUrl = String(request);
        const isBackendApi =
          !reqUrl.startsWith("http") || reqUrl.startsWith(baseURL);

        if (cookie && isBackendApi) {
          options.headers = { ...(options.headers || {}), cookie } as any;
        }
      }
    },
    onResponseError({ response }) {
      // 공통 로깅
      console.error("[API ERROR]", response.status, response._data);
    },
  });

  return { provide: { api } };
});
