/**
 * Onboarding Page Query
 *
 * Handles authentication and driver status checks for the onboarding page.
 */

import { Result } from '@/lib/contracts/Result';
import { PresentationError } from '@/lib/contracts/page-queries/PresentationError';
import { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { OnboardingService } from '@/lib/services/onboarding/OnboardingService';
import { OnboardingPageViewData } from '@/lib/view-data/OnboardingPageViewData';
import { OnboardingPageViewDataBuilder } from '@/lib/builders/view-data/OnboardingPageViewDataBuilder';

export class OnboardingPageQuery implements PageQuery<OnboardingPageViewData, void, PresentationError> {
  async execute(): Promise<Result<OnboardingPageViewData, PresentationError>> {
    const onboardingService = new OnboardingService();
    
    // Check if user is already onboarded
    const driverCheckResult = await onboardingService.checkCurrentDriver();
    
    if (driverCheckResult.isErr()) {
      const error = driverCheckResult.getError();
      
      // Map domain errors to presentation errors
      if (error.type === 'unauthorized') {
        return Result.err('unauthorized');
      } else if (error.type === 'notFound') {
        // No driver found means not onboarded yet - this is OK
        const output = OnboardingPageViewDataBuilder.build(null);
        return Result.ok(output);
      } else if (error.type === 'serverError' || error.type === 'networkError') {
        return Result.err('serverError');
      } else {
        return Result.err('unknown');
      }
    }
    
    const driver = driverCheckResult.unwrap();
    const output = OnboardingPageViewDataBuilder.build(driver);
    return Result.ok(output);
  }

  // Static factory method for convenience
  static async execute(): Promise<Result<OnboardingPageViewData, PresentationError>> {
    const query = new OnboardingPageQuery();
    return query.execute();
  }
}