import { clearAuthToken, getAuthToken, getLanguage, isPublicEndpoint } from "./auth.js";
import { getApiBaseUrl, getSecurePath } from "./settings.js";

export const publicEndpoints = [
  "/passport/auth/login",
  "/passport/auth/token2Login",
  "/passport/auth/register",
  "/guest/comm/config",
  "/passport/comm/sendEmailVerify",
  "/passport/auth/forget",
];

export function buildAdminPath(pathname) {
  const securePath = String(getSecurePath() || "").replace(/^\/+/, "");
  const normalized = pathname.startsWith("/") ? pathname : `/${pathname}`;
  return `${securePath}${normalized}`;
}

function resolveApiUrl(pathname, isPublic) {
  const normalized = pathname.startsWith("/") ? pathname : `/${pathname}`;
  if (normalized.startsWith("http")) {
    return normalized;
  }

  if (isPublic) {
    return `${getApiBaseUrl()}${normalized}`;
  }

  const securePath = String(getSecurePath() || "").replace(/^\/+/, "");
  return `${getApiBaseUrl()}/${securePath}${normalized}`;
}

export function buildRequestDescriptor(method, pathname, options = {}) {
  const token = getAuthToken();
  const apiPath = pathname.split("?")[0];
  const headers = {
    "Content-Type": "application/json",
    "Content-Language": getLanguage(),
    ...(options.headers || {}),
  };

  if (!isPublicEndpoint(apiPath, publicEndpoints) && token) {
    headers.Authorization = token;
  }

  return {
    method,
    url: resolveApiUrl(pathname, isPublicEndpoint(apiPath, publicEndpoints)),
    headers,
    body: options.body,
    securePath: getSecurePath(),
  };
}

export function handleHttpError(statusCode) {
  if (statusCode === 401 || statusCode === 403) {
    clearAuthToken();
  }
}
