import { Result } from '@core/shared/domain/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { Driver } from '../../domain/entities/Driver';
import type { DriverRepository } from '../../domain/repositories/DriverRepository';
import type { LeagueMembershipRepository } from '../../domain/repositories/LeagueMembershipRepository';
import type { LeagueRepository } from '../../domain/repositories/LeagueRepository';

export interface GetLeagueJoinRequestsInput {
  leagueId: string;
}

export type GetLeagueJoinRequestsErrorCode = 'LEAGUE_NOT_FOUND' | 'REPOSITORY_ERROR';

export interface LeagueJoinRequestWithDriver {
  id: string;
  leagueId: string;
  driverId: string;
  requestedAt: Date;
  message?: string;
  driver: Driver;
}

export interface GetLeagueJoinRequestsResult {
  joinRequests: LeagueJoinRequestWithDriver[];
}

export class GetLeagueJoinRequestsUseCase {
  constructor(
    private readonly leagueMembershipRepository: LeagueMembershipRepository,
    private readonly driverRepository: DriverRepository,
    private readonly leagueRepository: LeagueRepository,
  ) {}

  async execute(
    input: GetLeagueJoinRequestsInput,
  ): Promise<Result<GetLeagueJoinRequestsResult, ApplicationErrorCode<GetLeagueJoinRequestsErrorCode, { message: string }>>> {
    try {
      const leagueExists = await this.leagueRepository.exists(input.leagueId);

      if (!leagueExists) {
        return Result.err({
          code: 'LEAGUE_NOT_FOUND',
          details: { message: 'League not found' },
        });
      }

      const joinRequests = await this.leagueMembershipRepository.getJoinRequests(input.leagueId);
      const driverIds = [...new Set(joinRequests.map(request => request.driverId.toString()))];
      const drivers = await Promise.all(driverIds.map(id => this.driverRepository.findById(id)));

      const driverMap = new Map(
        drivers.filter((driver): driver is Driver => driver !== null).map(driver => [driver.id, driver]),
      );

      const enrichedJoinRequests: LeagueJoinRequestWithDriver[] = joinRequests
        .filter(request => driverMap.has(request.driverId.toString()))
        .map(request => ({
          id: request.id,
          leagueId: request.leagueId.toString(),
          driverId: request.driverId.toString(),
          requestedAt: request.requestedAt.toDate(),
          ...(request.message !== undefined && { message: request.message }),
          driver: driverMap.get(request.driverId.toString())!,
        }));

      const result: GetLeagueJoinRequestsResult = {
        joinRequests: enrichedJoinRequests,
      };

      return Result.ok(result);
    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : 'Failed to load league join requests';

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