import type { ModuleKey } from "@platform-types";

import { appendSessionToUrl } from "../lib/session";

export interface PortalRuntimeConfig {
  apiHubBaseUrl: string;
  llmBaseUrl: string;
  moduleUrls: Partial<Record<ModuleKey, string>>;
}

function normalizeModuleUrl(url: string): string {
  if (typeof window === "undefined") {
    return url;
  }

  try {
    const parsedUrl = new URL(url, window.location.origin);
    if (parsedUrl.hostname === "localhost" || parsedUrl.hostname === "127.0.0.1") {
      parsedUrl.protocol = window.location.protocol;
      parsedUrl.hostname = window.location.hostname;
    }
    return parsedUrl.toString();
  } catch {
    return url;
  }
}

export const portalRuntimeConfig: PortalRuntimeConfig = {
  apiHubBaseUrl: import.meta.env.VITE_API_HUB_BASE_URL || "/api",
  llmBaseUrl: import.meta.env.VITE_LLM_BASE_URL || "http://amicifede.ddns.net:1234/v1",
  moduleUrls: {
    prenotazioni: normalizeModuleUrl(import.meta.env.VITE_PRENOTAZIONI_MODULE_URL || "http://localhost:3100"),
    menu: normalizeModuleUrl(import.meta.env.VITE_MENU_MODULE_URL || "http://localhost:3200/"),
    ordini: normalizeModuleUrl(import.meta.env.VITE_ORDINI_MODULE_URL || "http://localhost:3300")
  }
};

function resolveModuleApiHubUrl(): string {
  if (typeof window === "undefined") {
    return portalRuntimeConfig.apiHubBaseUrl;
  }

  try {
    return new URL(portalRuntimeConfig.apiHubBaseUrl, window.location.origin).toString();
  } catch {
    return portalRuntimeConfig.apiHubBaseUrl;
  }
}

function appendQueryParam(url: string, key: string, value: string): string {
  try {
    const parsedUrl = new URL(url, window.location.origin);
    parsedUrl.searchParams.set(key, value);
    return parsedUrl.toString();
  } catch {
    return url;
  }
}

export function getModuleLaunchUrl(moduleKey: ModuleKey): string | null {
  const url = portalRuntimeConfig.moduleUrls[moduleKey] || null;
  if (!url) {
    return null;
  }

  if (moduleKey === "ordini") {
    return appendSessionToUrl(url);
  }

  if (moduleKey === "prenotazioni") {
    return appendSessionToUrl(url);
  }

  if (moduleKey === "menu") {
    const withSession = appendSessionToUrl(url);
    return appendQueryParam(withSession, "api", resolveModuleApiHubUrl());
  }

  return url;
}
