import { ProfileViewDataBuilder } from '@/lib/builders/view-data/ProfileViewDataBuilder';
import { Result } from '@/lib/contracts/Result';
import { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { PresentationError } from '@/lib/contracts/page-queries/PresentationError';
import { SessionGateway } from '@/lib/gateways/SessionGateway';
import { DriverProfileService } from '@/lib/services/drivers/DriverProfileService';
import type { ProfileViewData } from '@/lib/view-data/ProfileViewData';

export class ProfilePageQuery implements PageQuery<ProfileViewData, void, PresentationError> {
  async execute(): Promise<Result<ProfileViewData, PresentationError>> {
    const sessionGateway = new SessionGateway();
    const session = await sessionGateway.getSession();

    if (!session?.user?.primaryDriverId) {
      return Result.err('notFound');
    }

    const service = new DriverProfileService();
    const profileResult = await service.getDriverProfile(session.user.primaryDriverId);

    if (profileResult.isErr()) {
      const error = profileResult.getError();
      if (error === 'notFound') return Result.err('notFound');
      if (error === 'unauthorized') return Result.err('unauthorized');
      if (error === 'serverError') return Result.err('serverError');
      return Result.err('unknown');
    }

    const dto = profileResult.unwrap();
    const viewData = ProfileViewDataBuilder.build(dto);
    return Result.ok(viewData);
  }
}
