const PLACEHOLDER_DOMAINS = new Set([
  'https://yourdomain.com',
  'http://yourdomain.com',
  'https://example.com',
  'http://example.com',
  'https://localhost',
]);

function isRealAppUrl(url: string | undefined): url is string {
  if (!url) return false;
  const trimmed = url.replace(/\/+$/, '');
  return !PLACEHOLDER_DOMAINS.has(trimmed);
}

export function resolveRequestOrigin(req: { headers: { get(name: string): string | null } }): string {
  const rawHost = req.headers.get('host');
  const originHeader = req.headers.get('origin');

  const fromOriginHeader = originHeader && !originHeader.startsWith('null') ? originHeader : null;
  const fromHost = rawHost ? `https://${rawHost}` : null;
  const fromEnvAppUrl = isRealAppUrl(process.env.NEXT_PUBLIC_APP_URL)
    ? process.env.NEXT_PUBLIC_APP_URL
    : null;
  const fromVercel = process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` : null;

  const resolved = fromOriginHeader ?? fromHost ?? fromEnvAppUrl ?? fromVercel;
  if (!resolved) {
    throw new Error(
      'Cannot resolve request origin: no host header, origin header, NEXT_PUBLIC_APP_URL, or VERCEL_URL is available.'
    );
  }
  return resolved;
}
