import type { ITeamMembershipRepository } from '../../domain/repositories/ITeamMembershipRepository';
import type { IDriverRepository } from '../../domain/repositories/IDriverRepository';
import type { IImageServicePort } from '../ports/IImageServicePort';
import type { TeamMembersResultDTO } from '../presenters/ITeamMembersPresenter';
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 members.
 */
export class GetTeamMembersUseCase implements AsyncUseCase<{ teamId: string }, TeamMembersResultDTO, '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<TeamMembersResultDTO, ApplicationErrorCode<'REPOSITORY_ERROR'>>> {
    this.logger.debug(`Executing GetTeamMembersUseCase for teamId: ${input.teamId}`);

    try {
      const memberships = await this.membershipRepository.getTeamMembers(input.teamId);
      this.logger.info(`Found ${memberships.length} memberships for teamId: ${input.teamId}`);

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

      for (const membership of memberships) {
        this.logger.debug(`Processing membership for driverId: ${membership.driverId}`);
        const driver = await this.driverRepository.findById(membership.driverId);
        if (driver) {
          driverNames[membership.driverId] = driver.name;
        } else {
          this.logger.warn(`Driver with ID ${membership.driverId} not found while fetching team members for team ${input.teamId}.`);
        }
        avatarUrls[membership.driverId] = this.imageService.getDriverAvatar(membership.driverId);
      }

      const dto: TeamMembersResultDTO = {
        memberships,
        driverNames,
        avatarUrls,
      };

      return Result.ok(dto);
    } catch (error) {
      this.logger.error(`Error in GetTeamMembersUseCase for teamId: ${input.teamId}`, error as Error, { teamId: input.teamId });
      return Result.err({ code: 'REPOSITORY_ERROR', details: { message: 'Failed to retrieve team members' } });
    }
  }
}