const DEFAULT_AUTH_CALLBACK_URL = '/chat';

/**
 * Return a canonical same-origin path for post-auth navigation.
 *
 * Parsing before comparing origins rejects protocol-relative URLs, backslash
 * variants, and control characters that the WHATWG parser normalizes away.
 */
export function resolveAuthCallbackURL(candidate: string | null, currentOrigin: string): string {
  if (!candidate?.startsWith('/')) return DEFAULT_AUTH_CALLBACK_URL;

  try {
    const expectedOrigin = new URL(currentOrigin).origin;
    const resolved = new URL(candidate, expectedOrigin);
    if (resolved.origin !== expectedOrigin || resolved.pathname.startsWith('//')) {
      return DEFAULT_AUTH_CALLBACK_URL;
    }

    return `${resolved.pathname}${resolved.search}${resolved.hash}`;
  } catch {
    return DEFAULT_AUTH_CALLBACK_URL;
  }
}
