/**
 * Allowlist open-redirect targets from API responses.
 * Never trust response.data.redirect blindly.
 */

const DEFAULT_ALLOWED_HOSTS = [
  'localhost',
  '127.0.0.1',
  'poskasir.my.id',
];

function hostAllowed(hostname: string, allowedHosts: string[]): boolean {
  const host = hostname.toLowerCase();
  return allowedHosts.some((raw) => {
    const a = raw.toLowerCase().replace(/^\./, '');
    // Explicit wildcard only: "*.example.com"
    if (a.startsWith('*.')) {
      const base = a.slice(2);
      return host === base || host.endsWith('.' + base);
    }
    // Exact hostname match only (no suffix phishing via evil.poskasir.my.id)
    return host === a;
  });
}

/**
 * Resolve a redirect URL safely. Returns fallback if untrusted / invalid.
 */
export function safeRedirect(
  url: string | null | undefined,
  fallback: string,
  extraHosts: string[] = []
): string {
  if (!url || typeof url !== 'string') {
    return fallback;
  }

  const trimmed = url.trim();
  if (!trimmed) {
    return fallback;
  }

  // Relative path on same origin
  if (trimmed.startsWith('/') && !trimmed.startsWith('//')) {
    if (typeof window !== 'undefined') {
      return `${window.location.origin}${trimmed}`;
    }
    return trimmed;
  }

  try {
    const base =
      typeof window !== 'undefined' ? window.location.origin : 'http://127.0.0.1';
    const parsed = new URL(trimmed, base);

    if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
      return fallback;
    }

    const allowed = [...DEFAULT_ALLOWED_HOSTS, ...extraHosts];
    if (typeof window !== 'undefined') {
      allowed.push(window.location.hostname);
    }

    // Also allow admin/backend host from env if absolute
    const api = process.env.NEXT_PUBLIC_API_URL || '';
    try {
      if (api.startsWith('http')) {
        allowed.push(new URL(api).hostname);
      }
    } catch {
      /* ignore */
    }

    const adminEnv = process.env.NEXT_PUBLIC_ADMIN_URL || '';
    try {
      if (adminEnv.startsWith('http')) {
        allowed.push(new URL(adminEnv).hostname);
      }
    } catch {
      /* ignore */
    }

    if (!hostAllowed(parsed.hostname, allowed)) {
      return fallback;
    }

    return parsed.toString();
  } catch {
    return fallback;
  }
}
