const DEFAULT_MAIL_APP_URL = "https://mail.officialsite.kr";
const DEFAULT_PUBLIC_SITE_URL = "https://officialsite.kr";
export const OFFICIAL_MAIL_GUIDE_URL = `${DEFAULT_PUBLIC_SITE_URL}/guide`;

function trimTrailingSlash(value: string) {
  return value.replace(/\/$/, "");
}

function pickHeaderValue(value: null | string) {
  return value?.split(",")[0]?.trim() ?? "";
}

export type SearchParamValue = string | string[] | undefined;

export function getMailAppUrl() {
  return process.env.NEXT_PUBLIC_MAIL_APP_URL?.trim() || DEFAULT_MAIL_APP_URL;
}

export function getPublicSiteUrl() {
  return process.env.NEXT_PUBLIC_APP_URL?.trim() || DEFAULT_PUBLIC_SITE_URL;
}

export function getPublicSiteAbsoluteUrl(path: string, baseUrl = getPublicSiteUrl()) {
  return new URL(path, `${trimTrailingSlash(baseUrl)}/`).toString();
}

export function getMailWorkspaceUrl(baseUrl = getMailAppUrl()) {
  return `${trimTrailingSlash(baseUrl)}/mail`;
}

export function getMailAbsoluteUrl(path: string, baseUrl = getMailAppUrl()) {
  return new URL(path, `${trimTrailingSlash(baseUrl)}/`).toString();
}

export function isLocalHostname(hostname: string) {
  const normalized = hostname.replace(/\.$/, "").toLowerCase();
  return (
    normalized === "localhost" ||
    normalized === "127.0.0.1" ||
    normalized === "::1" ||
    normalized === "[::1]"
  );
}

export function isLocalOrigin(origin: string) {
  try {
    return isLocalHostname(new URL(origin).hostname);
  } catch {
    return false;
  }
}

export function resolveOriginFromHeaders(
  headerStore: Pick<Headers, "get">,
  fallbackUrl = getMailAppUrl(),
) {
  const forwardedHost = pickHeaderValue(headerStore.get("x-forwarded-host"));
  const forwardedProto = pickHeaderValue(headerStore.get("x-forwarded-proto"));

  if (forwardedHost) {
    return `${forwardedProto || "https"}://${forwardedHost}`;
  }

  const origin = pickHeaderValue(headerStore.get("origin"));

  if (origin) {
    try {
      return new URL(origin).origin;
    } catch {
      // Ignore malformed origin headers and fall through.
    }
  }

  const host = pickHeaderValue(headerStore.get("host"));

  if (host) {
    const protocol =
      forwardedProto || (host.includes("localhost") || host.startsWith("127.0.0.1") ? "http" : "https");
    return `${protocol}://${host}`;
  }

  try {
    return new URL(fallbackUrl).origin;
  } catch {
    return DEFAULT_MAIL_APP_URL;
  }
}

export function resolveMailAppUrlFromHeaders(headerStore: Pick<Headers, "get">) {
  const origin = resolveOriginFromHeaders(headerStore);
  return isLocalOrigin(origin) ? origin : getMailAppUrl();
}

export function buildMailEntryUrl(
  user?: { mailConfigured: boolean } | null,
  baseUrl = getMailAppUrl(),
) {
  const workspaceUrl = getMailWorkspaceUrl(baseUrl);

  if (!user) {
    return workspaceUrl;
  }

  return `${workspaceUrl}${
    user.mailConfigured ? "?folder=all" : "?panel=setup&section=domain"
  }`;
}

export function toSearchString(params: Record<string, SearchParamValue>) {
  const searchParams = new URLSearchParams();

  for (const [key, value] of Object.entries(params)) {
    if (Array.isArray(value)) {
      for (const item of value) {
        if (item) {
          searchParams.append(key, item);
        }
      }

      continue;
    }

    if (value) {
      searchParams.set(key, value);
    }
  }

  const query = searchParams.toString();
  return query ? `?${query}` : "";
}
