import axios from "axios";
import { SESSION_EXCHANGE_BY_AUD } from "./tokenClaims.js";
import { normalizeAuth } from "./storage.js";
import {
  roleFromJwt,
  userFromJwt,
  rolesFromJwt,
  roleIdsFromJwt,
} from "./jwtPayload.js";

function resolveApiOrigin() {
  if (typeof import.meta !== "undefined" && import.meta.env) {
    const raw = import.meta.env.VITE_API_BASE_URL;
    if (raw != null && String(raw).trim() !== "") {
      const trimmed = String(raw).trim().replace(/\/+$/, "");
      // Relative API prefix (e.g. /api/ptw) — session routes live on the app origin.
      if (trimmed.startsWith("/")) {
        return "";
      }
      if (/^https?:\/\//i.test(trimmed)) {
        return trimmed
          .replace(/\/api\/[^/]+$/i, "")
          .replace(/\/api$/i, "");
      }
      return trimmed;
    }
  }
  if (typeof process !== "undefined" && process.env) {
    const cra =
      process.env.REACT_APP_PROXY_TARGET ||
      process.env.REACT_APP_API_BASE_URL;
    if (cra != null && String(cra).trim() !== "") {
      const trimmed = String(cra).trim().replace(/\/+$/, "");
      if (trimmed.startsWith("/")) {
        return "";
      }
      return trimmed
        .replace(/\/api\/[^/]+$/i, "")
        .replace(/\/api$/i, "");
    }
  }
  return "";
}

export async function exchangeLaunchToken(launchToken, aud) {
  const path = SESSION_EXCHANGE_BY_AUD[aud];
  if (!path) {
    throw new Error(`No session exchange route for audience: ${aud}`);
  }
  const origin = resolveApiOrigin();
  const url = `${origin}${path}`;
  const res = await axios.post(
    url,
    {},
    {
      headers: { Authorization: `Bearer ${launchToken}` },
      timeout: 15000,
    }
  );
  const token = res.data?.token;
  if (!token) {
    throw new Error("Session exchange did not return a token");
  }
  return normalizeAuth({
    token,
    user: res.data?.user || userFromJwt(token),
    roles: res.data?.user?.roles || rolesFromJwt(token),
    roleIds: res.data?.user?.roleIds || roleIdsFromJwt(token),
    role: roleFromJwt(token),
  });
}
