/**
 * Maps a thrown route-guard error to a redirect target.
 *
 * "auth is auth, role is role": ONLY genuine unauthentication (AUTH_REQUIRED)
 * redirects to /login. Every authenticated-but-blocked code goes to a real,
 * authenticated page (/vendor/register or /blocked) — never /login, never a 404.
 * Unknown errors are rethrown so real bugs surface as 500s, not silent bounces.
 *
 * Discriminates on the stable `code` string literal (AuthRequiredError /
 * ForbiddenError both carry one) to avoid importing the middleware module.
 */
function errCode(err: unknown): string | undefined {
  if (err && typeof err === 'object' && 'code' in err) {
    const c = (err as { code?: unknown }).code;
    return typeof c === 'string' ? c : undefined;
  }
  return undefined;
}

export function resolveGuardRedirect(err: unknown, currentPath: string): string {
  switch (errCode(err)) {
    case 'AUTH_REQUIRED':
      return `/login?redirect=${encodeURIComponent(currentPath)}`;
    case 'VENDOR_REQUIRED':
      return '/vendor/register';
    case 'VENDOR_SUSPENDED':
      return '/blocked?reason=suspended';
    case 'ACCOUNT_FROZEN':
      return '/blocked?reason=frozen';
    case 'ADMIN_REQUIRED':
      return '/blocked?reason=admin';
    default:
      // Not a recognized guard error — surface the real failure.
      throw err;
  }
}
