import { getMasterDashboardUrl } from "hse-auth";
import { getStoredAuth } from "../services/api.js";

/** SAT portal — SAT-only admin screens (activity log, users, etc.). */
export const SAT_PORTAL_URL =
  import.meta.env.VITE_SAT_PORTAL_URL || "http://localhost:3000";

function masterDashboardBaseUrl() {
  return String(getMasterDashboardUrl() || "").replace(/\/$/, "");
}

/**
 * Exchange the current SWI session for a Master login JWT (SSO handoff).
 * @returns {Promise<string|null>}
 */
async function fetchMasterHandoffToken() {
  const sessionToken = getStoredAuth()?.token;
  if (!sessionToken) return null;

  try {
    const res = await fetch("/api/master/auth/app-return", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${sessionToken}`,
        Accept: "application/json",
      },
    });
    if (!res.ok) return null;
    const data = await res.json().catch(() => null);
    const token = data?.token;
    return token && String(token).trim() ? String(token).trim() : null;
  } catch {
    return null;
  }
}

function buildMasterUrl(path = "/", query = {}, handoffToken = null) {
  const base = masterDashboardBaseUrl();
  const pathNorm = path.startsWith("/") ? path : `/${path}`;
  const params = new URLSearchParams();
  for (const [key, value] of Object.entries(query || {})) {
    if (value != null && value !== "") params.set(key, String(value));
  }
  if (handoffToken) {
    params.set("token", handoffToken);
  }
  const qs = params.toString();
  return `${base}${pathNorm}${qs ? `?${qs}` : ""}`;
}

/** Standalone HSE Master Dashboard (project launcher) — port 5174 in dev. */
export async function openMasterDashboard() {
  const handoffToken = await fetchMasterHandoffToken();
  window.location.assign(buildMasterUrl("/", {}, handoffToken));
}

/**
 * Open a route on the Master Dashboard (personal dashboard lives here).
 * Uses app-return SSO so the user is not sent to Master login.
 * @param {string} path e.g. `/personalized-dashboard`
 * @param {Record<string, string>} [query]
 */
export async function openMasterDashboardPath(path = "/", query = {}) {
  const handoffToken = await fetchMasterHandoffToken();
  window.location.assign(buildMasterUrl(path, query, handoffToken));
}

/**
 * Open a route on the SAT portal (not the Master Dashboard).
 * @param {string} path e.g. `/users`
 */
export function openSatPortal(path = "/") {
  const auth = getStoredAuth();
  const token = auth?.token;
  const base = String(SAT_PORTAL_URL || "").replace(/\/$/, "");
  const pathNorm = path.startsWith("/") ? path : `/${path}`;
  let url = `${base}${pathNorm}`;
  if (token) {
    const sep = url.includes("?") ? "&" : "?";
    url += `${sep}token=${encodeURIComponent(token)}`;
  }
  window.location.assign(url);
}

export { getMasterDashboardUrl };
