import type { ILeagueMembershipRepository } from '../../domain/repositories/ILeagueMembershipRepository';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { AsyncUseCase } from '@core/shared/application';
import { randomUUID } from 'crypto';
import type { ApproveLeagueJoinRequestUseCaseParams } from '../dto/ApproveLeagueJoinRequestUseCaseParams';
import type { ApproveLeagueJoinRequestResultDTO } from '../dto/ApproveLeagueJoinRequestResultDTO';
import { JoinedAt } from '../../domain/value-objects/JoinedAt';

export class ApproveLeagueJoinRequestUseCase implements AsyncUseCase<ApproveLeagueJoinRequestUseCaseParams, ApproveLeagueJoinRequestResultDTO, string> {
  constructor(private readonly leagueMembershipRepository: ILeagueMembershipRepository) {}

  async execute(params: ApproveLeagueJoinRequestUseCaseParams): Promise<Result<ApproveLeagueJoinRequestResultDTO, ApplicationErrorCode<string>>> {
    const requests = await this.leagueMembershipRepository.getJoinRequests(params.leagueId);
    const request = requests.find(r => r.id === params.requestId);
    if (!request) {
      return Result.err({ code: 'JOIN_REQUEST_NOT_FOUND' });
    }
    await this.leagueMembershipRepository.removeJoinRequest(params.requestId);
    await this.leagueMembershipRepository.saveMembership({
      id: randomUUID(),
      leagueId: params.leagueId,
      driverId: request.driverId,
      role: 'member',
      status: 'active',
      joinedAt: JoinedAt.create(new Date()),
    });
    const dto: ApproveLeagueJoinRequestResultDTO = { success: true, message: 'Join request approved.' };
    return Result.ok(dto);
  }
}