import axios from "axios";
import { getMasterLoginToken, clearMasterStoredAuth } from "hse-auth";

const PROJECT_APP_MAP = {
  sat: "sat",
  "risk-assessment": "risk",
  swi: "swi",
  "project-3": "ptw",
};

const SAT_APP_URL =
  import.meta.env.VITE_SAT_URL || "http://localhost:3000";
const RISK_APP_URL =
  import.meta.env.VITE_RISK_ASSESSMENT_URL || "http://localhost:5173";
const SWI_APP_URL = import.meta.env.VITE_SWI_URL || "http://localhost:5175";
const PTW_APP_URL = import.meta.env.VITE_PTW_URL || "http://localhost:5176";

function projectBaseUrl(projectId) {
  if (projectId === "sat") {
    return `${String(SAT_APP_URL).replace(/\/+$/, "")}/dashboard`;
  }
  if (projectId === "risk-assessment") {
    return String(RISK_APP_URL || "").trim() || null;
  }
  if (projectId === "swi") {
    return String(SWI_APP_URL || "").trim() || null;
  }
  if (projectId === "project-3") {
    return String(PTW_APP_URL || "").trim() || null;
  }
  return null;
}

function appendToken(baseUrl, token) {
  const separator = baseUrl.includes("?") ? "&" : "?";
  return `${baseUrl}${separator}token=${encodeURIComponent(token)}`;
}

/**
 * Request a short-lived launch JWT and return the child app URL with ?token=.
 */
export async function buildAppLaunchUrl(projectId) {
  const baseUrl = projectBaseUrl(projectId);
  if (!baseUrl) return null;

  const app = PROJECT_APP_MAP[projectId];
  const loginToken = getMasterLoginToken();
  if (!app || !loginToken) {
    return baseUrl;
  }

  const apiBase = import.meta.env.VITE_API_BASE_URL || "";
  try {
    const res = await axios.post(
      `${apiBase}/api/master/auth/app-launch`,
      { app },
      {
        headers: { Authorization: `Bearer ${loginToken}` },
        timeout: 15000,
      }
    );

    const launchToken = res.data?.token;
    if (!launchToken) {
      throw new Error("App launch did not return a token");
    }
    return appendToken(baseUrl, launchToken);
  } catch (error) {
    if (error.response?.status === 401) {
      clearMasterStoredAuth();
      window.location.replace("/login");
    }
    throw error;
  }
}

export function isLaunchableProject(projectId) {
  return Object.prototype.hasOwnProperty.call(PROJECT_APP_MAP, projectId);
}

export function isExternalAppUrl(route) {
  return typeof route === "string" && /^https?:\/\//i.test(route.trim());
}

export async function openProject(projectId, navigate) {
  const url = await buildAppLaunchUrl(projectId);
  if (!url) return;
  if (isExternalAppUrl(url)) {
    window.location.assign(url.trim());
    return;
  }
  navigate(url);
}
