import {
  AUTH_STORAGE_KEY,
  getToken,
  getStoredAuth,
  getHseLoginUrl,
  getMasterDashboardUrl,
} from "hse-auth";

/** Strip trailing slashes and a trailing `/api` so callers can use `${BASE}/api/...` without doubling. */
export function normalizeApiBaseUrl(raw) {
  let u = String(raw ?? "").trim();
  if (!u) return "";
  u = u.replace(/\/+$/, "");
  if (/\/api$/i.test(u)) {
    u = u.replace(/\/api$/i, "");
  }
  return u;
}

function resolveApiBaseUrl() {
  const raw = import.meta.env.VITE_API_BASE_URL;
  if (raw !== undefined && String(raw).trim() !== "") {
    return normalizeApiBaseUrl(raw) || "http://localhost:3000";
  }
  if (import.meta.env.DEV) {
    return "";
  }
  return "http://localhost:3000";
}

export const API_BASE_URL = resolveApiBaseUrl();

export function uploadAssetUrl(pathOrUrl) {
  if (pathOrUrl == null || pathOrUrl === "") return null;
  if (typeof pathOrUrl !== "string") return null;
  const raw = pathOrUrl.trim();
  if (!raw) return null;
  if (raw.startsWith("http") || raw.startsWith("data:")) return raw;
  return `${API_BASE_URL}/${raw.replace(/\\/g, "/")}`;
}

export { AUTH_STORAGE_KEY };

export function getSatLoginUrl() {
  return getHseLoginUrl();
}

export function getAuthToken() {
  return getToken() || "";
}

export function getSessionUserId() {
  const auth = getStoredAuth();
  if (!auth) return "";
  const u = auth.user || {};
  const id = u.userId ?? u.user_id;
  if (id != null && id !== "") return String(id);
  return "";
}

export { getMasterDashboardUrl };
