const GLOBAL_ACCOUNT_ID =
  process.env.NEXT_PUBLIC_CLASSWISE_GLOBAL_ACCOUNT_ID || "1162885000381811255";

const GLOBAL_FALLBACK_DOMAINS = new Set([
  "localhost",
  "127.0.0.1",
  "web.youngengineers.org",
  "preview.youngengineers.org",
]);

type FranchiseLike = {
  zoho_franchise_id?: string | null;
  zoho_account_link?: string | null;
} | null | undefined;

/**
 * Extract Zoho CRM account id from a Zoho Accounts URL
 * (e.g. .../tab/Accounts/1162885000381811255).
 */
export function extractZohoAccountIdFromLink(link?: string | null): string | null {
  if (!link || typeof link !== "string") return null;

  const accountsMatch = link.match(/\/Accounts\/(\d+)/i);
  if (accountsMatch?.[1]) return accountsMatch[1];

  return null;
}

export function shouldUseClasswiseGlobalAccount(domain?: string | null): boolean {
  if (!domain) return false;
  const host = domain.replace(/^https?:\/\//, "").split(":")[0].toLowerCase();
  return GLOBAL_FALLBACK_DOMAINS.has(host);
}

/**
 * Resolve the Classwise `account_id` param. Never use internal franchise/user ids.
 */
/** Zoho CRM account ids are long numeric strings; short ids are usually internal franchise ids. */
export function isLikelyZohoAccountId(value?: string | null): boolean {
  const trimmed = String(value ?? "").trim();
  return /^\d{10,}$/.test(trimmed);
}

export function resolveClasswiseAccountId(options: {
  tenantZohoId?: string | null;
  franchise?: FranchiseLike;
  domain?: string | null;
}): string | null {
  const candidates = [
    isLikelyZohoAccountId(options.tenantZohoId) ? options.tenantZohoId : null,
    options.franchise?.zoho_franchise_id,
    extractZohoAccountIdFromLink(options.franchise?.zoho_account_link),
  ];

  for (const candidate of candidates) {
    const trimmed = String(candidate ?? "").trim();
    if (trimmed && isLikelyZohoAccountId(trimmed)) return trimmed;
  }

  if (shouldUseClasswiseGlobalAccount(options.domain)) {
    return GLOBAL_ACCOUNT_ID;
  }

  return null;
}

export function resolveClasswiseAccountIdFromHostname(
  tenantZohoId?: string | null,
  franchise?: FranchiseLike
): string | null {
  const domain =
    typeof window !== "undefined" ? window.location.hostname : null;

  return resolveClasswiseAccountId({
    tenantZohoId,
    franchise,
    domain,
  });
}
