import type { ITeamMembershipRepository } from '../../domain/repositories/ITeamMembershipRepository';
import type { IDriverRepository } from '../../domain/repositories/IDriverRepository';
import type { IImageServicePort } from '../ports/IImageServicePort';
import type { TeamJoinRequestsResultDTO } from '../presenters/ITeamJoinRequestsPresenter';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { AsyncUseCase } from '@core/shared/application';
import type { Logger } from '@core/shared/application';

/**
 * Use Case for retrieving team join requests.
 */
export class GetTeamJoinRequestsUseCase implements AsyncUseCase<{ teamId: string }, TeamJoinRequestsResultDTO, 'REPOSITORY_ERROR'>
{
  constructor(
    private readonly membershipRepository: ITeamMembershipRepository,
    private readonly driverRepository: IDriverRepository,
    private readonly imageService: IImageServicePort,
    private readonly logger: Logger,
  ) {}

  async execute(input: { teamId: string }): Promise<Result<TeamJoinRequestsResultDTO, ApplicationErrorCode<'REPOSITORY_ERROR'>>> {
    this.logger.debug('Executing GetTeamJoinRequestsUseCase', { teamId: input.teamId });

    try {
      const requests = await this.membershipRepository.getJoinRequests(input.teamId);
      this.logger.info('Successfully retrieved team join requests', { teamId: input.teamId, count: requests.length });

      const driverNames: Record<string, string> = {};
      const avatarUrls: Record<string, string> = {};

      for (const request of requests) {
        const driver = await this.driverRepository.findById(request.driverId);
        if (driver) {
          driverNames[request.driverId] = driver.name;
        } else {
          this.logger.warn(`Driver not found for ID: ${request.driverId} during join request processing.`);
        }
        avatarUrls[request.driverId] = this.imageService.getDriverAvatar(request.driverId);
        this.logger.debug('Processed driver details for join request', { driverId: request.driverId });
      }

      const dto: TeamJoinRequestsResultDTO = {
        requests,
        driverNames,
        avatarUrls,
      };

      return Result.ok(dto);
    } catch (error) {
      this.logger.error('Error retrieving team join requests', { teamId: input.teamId, err: error });
      return Result.err({ code: 'REPOSITORY_ERROR', details: { message: 'Failed to retrieve team join requests' } });
    }
  }
}