/**
 * GetTrackImagePageQuery
 *
 * Server-side composition for track image media route.
 */

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

export class GetTrackImagePageQuery implements PageQuery<TrackImageViewData, { trackId: string }> {
  async execute(params: { trackId: string }): Promise<Result<TrackImageViewData, PresentationError>> {
    try {
      const service = new MediaService();
      const apiDtoResult = await service.getTrackImage(params.trackId);

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

      const output = TrackImageViewDataBuilder.build(apiDtoResult.unwrap());
      return Result.ok(output);
    } catch (err) {
      console.error('GetTrackImagePageQuery failed:', err);
      return Result.err('serverError');
    }
  }

  static async execute(params: { trackId: string }): Promise<Result<TrackImageViewData, PresentationError>> {
    const query = new GetTrackImagePageQuery();
    return query.execute(params);
  }
}