import { SignupViewDataBuilder } from '@/lib/builders/view-data/SignupViewDataBuilder';
import { SignupViewData } from '@/lib/builders/view-data/types/SignupViewData';
import { Result } from '@/lib/contracts/Result';
import { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { AuthPageService } from '@/lib/services/auth/AuthPageService';
import { SearchParamParser } from '@/lib/routing/search-params/SearchParamParser';

export class SignupPageQuery implements PageQuery<SignupViewData, URLSearchParams | Record<string, string | string[] | undefined>> {
  async execute(searchParams: URLSearchParams | Record<string, string | string[] | undefined>): Promise<Result<SignupViewData, string>> {
    // Parse and validate search parameters
    const parsedResult = SearchParamParser.parseAuth(searchParams);
    if (parsedResult.isErr()) {
      return Result.err(`Invalid search parameters: ${parsedResult.getError()}`);
    }

    const { returnTo, token } = parsedResult.unwrap();

    try {
      // Use service to process parameters
      const authService = new AuthPageService();
      const serviceResult = await authService.processSignupParams({ returnTo, token });
      
      if (serviceResult.isErr()) {
        return Result.err(serviceResult.getError().message);
      }

      // Transform to ViewData using builder
      const viewData = SignupViewDataBuilder.build(serviceResult.unwrap());
      return Result.ok(viewData);
    } catch (error: any) {
      return Result.err(error.message || 'Failed to execute signup page query');
    }
  }

  // Static factory method for convenience
  static async execute(searchParams: URLSearchParams | Record<string, string | string[] | undefined>): Promise<Result<SignupViewData, string>> {
    const query = new SignupPageQuery();
    return query.execute(searchParams);
  }
}
