export function nextAuthSuccessState(path, data = {}, requestedNext = '') {
  if (isRegisterPath(path)) {
    return {
      mode: 'login',
      path: '/login',
      message: String(data.message || '注册成功，请先验证邮箱，验证后等待管理员审核。'),
      redirectTo: ''
    };
  }
  return {
    mode: 'login',
    path: '/login',
    message: '',
    redirectTo: safeInternalPath(data.redirectTo || requestedNext, '/overview')
  };
}

export function safeInternalPath(value, fallback = '') {
  const candidate = String(value || '').trim();
  if (!candidate || !candidate.startsWith('/') || candidate.startsWith('//')) return fallback;
  if (candidate.includes('\\') || /[\u0000-\u001f\u007f]/.test(candidate)) return fallback;

  try {
    const parsed = new URL(candidate, 'http://mailhub.local');
    if (parsed.origin !== 'http://mailhub.local') return fallback;
    if (
      ['/login', '/register', '/forgot-password', '/resend-verification', '/reset-password', '/landing.html', '/healthz'].includes(parsed.pathname)
      || ['/api', '/assets', '/t'].some((prefix) => parsed.pathname === prefix || parsed.pathname.startsWith(`${prefix}/`))
    ) {
      return fallback;
    }
    return `${parsed.pathname}${parsed.search}${parsed.hash}`;
  } catch {
    return fallback;
  }
}

export function authModeFromLocation(pathname, search = '') {
  const path = String(pathname || '');
  if (path.endsWith('/register')) return { mode: 'register', token: '' };
  if (path.endsWith('/forgot-password')) return { mode: 'forgot', token: '' };
  if (path.endsWith('/resend-verification')) return { mode: 'resend', token: '' };
  if (path.endsWith('/reset-password')) {
    return {
      mode: 'reset',
      token: new URLSearchParams(String(search || '')).get('token') || ''
    };
  }
  return { mode: 'login', token: '' };
}

function isRegisterPath(path) {
  return String(path || '').endsWith('/register');
}
