/**
 * GetAvatarPageQuery
 *
 * Server-side composition for avatar media route.
 * Fetches avatar binary data and transforms to ViewData.
 */

import { PageQuery } from '@/lib/contracts/page-queries/PageQuery';
import { Result } from '@/lib/contracts/Result';
import { MediaService } from '@/lib/services/media/MediaService';
import { AvatarViewDataBuilder } from '@/lib/builders/view-data/AvatarViewDataBuilder';
import { AvatarViewData } from '@/lib/view-data/AvatarViewData';
import { PresentationError, mapToPresentationError } from '@/lib/contracts/page-queries/PresentationError';

export class GetAvatarPageQuery implements PageQuery<AvatarViewData, { driverId: string }> {
  async execute(params: { driverId: string }): Promise<Result<AvatarViewData, PresentationError>> {
    try {
      // Manual construction: Service creates its own dependencies
      const service = new MediaService();
      
      // Fetch avatar data
      const apiDtoResult = await service.getAvatar(params.driverId);

      if (apiDtoResult.isErr()) {
        return Result.err(mapToPresentationError(apiDtoResult.getError()));
      }

      // Transform to ViewData using builder
      const output = AvatarViewDataBuilder.build(apiDtoResult.unwrap());

      return Result.ok(output);
    } catch (err) {
      console.error('GetAvatarPageQuery failed:', err);
      return Result.err('serverError');
    }
  }

  // Static method to avoid object construction in server code
  static async execute(params: { driverId: string }): Promise<Result<AvatarViewData, PresentationError>> {
    const query = new GetAvatarPageQuery();
    return query.execute(params);
  }
}