/**
 * Use Case: SelectAvatarUseCase
 * 
 * Allows a user to select one of the generated avatars as their profile avatar.
 */

import type { AsyncUseCase, Logger } from '@core/shared/application';
import type { IAvatarGenerationRepository } from '../../domain/repositories/IAvatarGenerationRepository';

export interface SelectAvatarCommand {
  requestId: string;
  userId: string;
  avatarIndex: number;
}

export interface SelectAvatarResult {
  success: boolean;
  selectedAvatarUrl?: string;
  errorMessage?: string;
}

export class SelectAvatarUseCase
  implements AsyncUseCase<SelectAvatarCommand, SelectAvatarResult> {
  constructor(
    private readonly avatarRepository: IAvatarGenerationRepository,
    private readonly logger: Logger,
  ) {}

  async execute(command: SelectAvatarCommand): Promise<SelectAvatarResult> {
    this.logger.debug(`Executing SelectAvatarUseCase for userId: ${command.userId}, requestId: ${command.requestId}, avatarIndex: ${command.avatarIndex}`);

    const request = await this.avatarRepository.findById(command.requestId);

    if (!request) {
      this.logger.info(`Avatar generation request not found for requestId: ${command.requestId}`);
      return {
        success: false,
        errorMessage: 'Avatar generation request not found',
      };
    }

    if (request.userId !== command.userId) {
      this.logger.info(`Permission denied for userId: ${command.userId} to select avatar for requestId: ${command.requestId}`);
      return {
        success: false,
        errorMessage: 'You do not have permission to select this avatar',
      };
    }

    if (request.status !== 'completed') {
      this.logger.info(`Avatar generation not completed for requestId: ${command.requestId}, current status: ${request.status}`);
      return {
        success: false,
        errorMessage: 'Avatar generation is not yet complete',
      };
    }

    try {
      request.selectAvatar(command.avatarIndex);
      await this.avatarRepository.save(request);

      const selectedAvatarUrl = request.selectedAvatarUrl;
      const result: SelectAvatarResult =
        selectedAvatarUrl !== undefined
          ? { success: true, selectedAvatarUrl }
          : { success: true };

      this.logger.info(`Avatar selected successfully for userId: ${command.userId}, requestId: ${command.requestId}, selectedAvatarUrl: ${selectedAvatarUrl}`);
      return result;
    } catch (error) {
      this.logger.error(`Failed to select avatar for userId: ${command.userId}, requestId: ${command.requestId}: ${error instanceof Error ? error.message : 'Unknown error'}`, error);
      return {
        success: false,
        errorMessage: error instanceof Error ? error.message : 'Failed to select avatar',
      };
    }
  }
}