// ใช้ NEXT_PUBLIC_API_BASE จาก docker-compose (ไม่ใช้ .env file)
export const API_BASE = process.env.NEXT_PUBLIC_API_BASE || "http://localhost:3001";

// NEW: querystring helper (รองรับ array)
export function qstr(params = {}) {
  const sp = new URLSearchParams();
  Object.entries(params).forEach(([k, v]) => {
    if (v === undefined || v === null || v === "") return;
    if (Array.isArray(v)) v.forEach((x) => sp.append(k, String(x)));
    else sp.set(k, String(v));
  });
  const s = sp.toString();
  return s ? `?${s}` : "";
}

// NEW: GET helper
export function apiGet(path, params = {}, opts = {}) {
  return api(`${path}${qstr(params)}`, { ...opts, method: "GET" });
}

export async function api(path, { method = "GET", body, headers = {}, cache = "no-store" } = {}) {
  const res = await fetch(`${API_BASE}${path}`, {
    method,
    headers: {
      "Content-Type": "application/json",
      ...headers,
    },
    body: body ? JSON.stringify(body) : undefined,
    credentials: "include",
    cache,
    next: { revalidate: 0 },
  });
  if (!res.ok) {
    const text = await res.text().catch(()=>"");
    throw new Error(`API ${method} ${path} ${res.status} ${text}`);
  }
  const ct = res.headers.get("content-type") || "";
  return ct.includes("application/json") ? res.json() : res.text();
}
