/**
 * Use Case: GetAvatarUseCase
 *
 * Handles the business logic for retrieving a driver's avatar.
 */

import type { IAvatarRepository } from '../../domain/repositories/IAvatarRepository';
import type { Logger, UseCaseOutputPort } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

export interface GetAvatarInput {
  driverId: string;
}

export interface GetAvatarResult {
  avatar: {
    id: string;
    driverId: string;
    mediaUrl: string;
    selectedAt: Date;
  };
}

export type GetAvatarErrorCode = 'AVATAR_NOT_FOUND' | 'REPOSITORY_ERROR';

export type GetAvatarApplicationError = ApplicationErrorCode<
  GetAvatarErrorCode,
  { message: string }
>;

export class GetAvatarUseCase {
  constructor(
    private readonly avatarRepo: IAvatarRepository,
    private readonly output: UseCaseOutputPort<GetAvatarResult>,
    private readonly logger: Logger,
  ) {}

  async execute(input: GetAvatarInput): Promise<Result<void, GetAvatarApplicationError>> {
    this.logger.info('[GetAvatarUseCase] Getting avatar', {
      driverId: input.driverId,
    });

    try {
      const avatar = await this.avatarRepo.findActiveByDriverId(input.driverId);

      if (!avatar) {
        return Result.err({
          code: 'AVATAR_NOT_FOUND',
          details: { message: 'Avatar not found' },
        });
      }

      this.output.present({
        avatar: {
          id: avatar.id,
          driverId: avatar.driverId,
          mediaUrl: avatar.mediaUrl.value,
          selectedAt: avatar.selectedAt,
        },
      });

      return Result.ok(undefined);
    } catch (error) {
      const err = error instanceof Error ? error : new Error(String(error));

      this.logger.error('[GetAvatarUseCase] Error getting avatar', err, {
        driverId: input.driverId,
      });

      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message: err.message ?? 'Unexpected repository error' },
      });
    }
  }
}