// src/lib/client/client.ts
import { createClient } from "@mercurjs/client";
import config from "virtual:mercur/config";

// src/utils/asset-url.ts
function assetUrl(path) {
  const base = (typeof __BASE__ !== "undefined" ? __BASE__ : "/").replace(
    /\/+$/,
    ""
  );
  const cleanPath = path.startsWith("/") ? path : `/${path}`;
  return `${base}${cleanPath}`;
}

// src/lib/client/client.ts
var backendUrl = config.backendUrl ?? "http://localhost:9000";
var sdk = createClient({
  baseUrl: backendUrl,
  fetchOptions: {
    credentials: "include"
  }
});
var fetchQuery = async (url, {
  method,
  body,
  query,
  headers
}) => {
  const params = Object.entries(query || {}).reduce((acc, [key, value]) => {
    if (value !== null && value !== void 0 && value !== "") {
      if (Array.isArray(value)) {
        const arrayParams = value.map(
          (item) => `${encodeURIComponent(key)}[]=${encodeURIComponent(item)}`
        ).join("&");
        if (acc) {
          acc += "&" + arrayParams;
        } else {
          acc = arrayParams;
        }
      } else {
        const separator = acc ? "&" : "";
        const serializedValue = typeof value === "object" ? JSON.stringify(value) : value;
        acc += `${separator}${encodeURIComponent(key)}=${encodeURIComponent(serializedValue)}`;
      }
    }
    return acc;
  }, "");
  const response = await fetch(
    `${backendUrl}${url}${params ? `?${params}` : ""}`,
    {
      method,
      credentials: "include",
      headers: {
        "Content-Type": "application/json",
        ...headers
      },
      body: body ? JSON.stringify(body) : null
    }
  );
  if (!response.ok) {
    const errorData = await response.json();
    if (response.status === 401) {
      window.location.href = `${assetUrl("/login")}?reason=Unauthorized`;
      return;
    }
    const error = new Error(errorData.message || "Server error");
    error.status = response.status;
    throw error;
  }
  return response.json();
};

export {
  assetUrl,
  sdk,
  fetchQuery
};
