import { redirect } from 'next/navigation';
import { OnboardingWizardClient } from '@/client-wrapper/OnboardingWizardClient';
import { OnboardingPageQuery } from '@/lib/page-queries/OnboardingPageQuery';
import { SearchParamBuilder } from '@/lib/routing/search-params/SearchParamBuilder';
import { routes } from '@/lib/routing/RouteConfig';

/**
 * Onboarding Page
 *
 * Server Component that handles authentication and authorization.
 * Redirects to login if not authenticated.
 * Redirects to dashboard if already onboarded.
 */
export default async function OnboardingPage() {
  // Use PageQuery to check if user is already onboarded
  const result = await OnboardingPageQuery.execute();
  
  if (result.isErr()) {
    const error = result.getError();
    
    if (error === 'unauthorized') {
      redirect(`${routes.auth.login}${SearchParamBuilder.auth(routes.protected.onboarding)}`);
    } else if (error === 'serverError' || error === 'networkError') {
      // Show error page or let them proceed with a warning
      // For now, we'll let them proceed
    }
  } else {
    const viewData = result.unwrap();
    
    if (viewData.isAlreadyOnboarded) {
      redirect(routes.protected.dashboard);
    }
  }

  return <OnboardingWizardClient />;
}