import type { ITeamRepository } from '../../domain/repositories/ITeamRepository';
import type { ITeamMembershipRepository } from '../../domain/repositories/ITeamMembershipRepository';
import type { AllTeamsResultDTO } from '../presenters/IAllTeamsPresenter';
import type { AsyncUseCase, Logger } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';

/**
 * Use Case for retrieving all teams.
 */
export class GetAllTeamsUseCase implements AsyncUseCase<void, AllTeamsResultDTO, 'REPOSITORY_ERROR'> {
  constructor(
    private readonly teamRepository: ITeamRepository,
    private readonly teamMembershipRepository: ITeamMembershipRepository,
    private readonly logger: Logger,
  ) {}

  async execute(): Promise<Result<AllTeamsResultDTO, ApplicationErrorCode<'REPOSITORY_ERROR', { message: string }>>> {
    this.logger.debug('Executing GetAllTeamsUseCase');

    try {
      const teams = await this.teamRepository.findAll();

      const enrichedTeams: AllTeamsResultDTO['teams'] = await Promise.all(
        teams.map(async (team) => {
          const memberCount = await this.teamMembershipRepository.countByTeamId(team.id);
          return {
            id: team.id,
            name: team.name,
            tag: team.tag,
            description: team.description,
            ownerId: team.ownerId,
            leagues: [...team.leagues],
            createdAt: team.createdAt,
            memberCount,
          };
        }),
      );

      const dto: AllTeamsResultDTO = {
        teams: enrichedTeams,
      };

      this.logger.debug('Successfully retrieved all teams.');
      return Result.ok(dto);
    } catch (error) {
      this.logger.error('Error retrieving all teams', error instanceof Error ? error : new Error(String(error)));
      return Result.err({
        code: 'REPOSITORY_ERROR',
        details: { message: error instanceof Error ? error.message : 'Unknown error occurred' },
      });
    }
  }
}