import type { UseCaseOutputPort } from '@core/shared/application';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { ILeagueMembershipRepository } from '../../domain/repositories/ILeagueMembershipRepository';

export type RejectLeagueJoinRequestInput = {
  leagueId: string;
  joinRequestId: string;
};

export type RejectLeagueJoinRequestResult = {
  success: boolean;
  message: string;
};

export class RejectLeagueJoinRequestUseCase {
  constructor(
    private readonly leagueMembershipRepository: ILeagueMembershipRepository,
  ) {}

  async execute(
    input: RejectLeagueJoinRequestInput,
    output: UseCaseOutputPort<RejectLeagueJoinRequestResult>,
  ): Promise<Result<void, ApplicationErrorCode<'JOIN_REQUEST_NOT_FOUND'>>> {
    const requests = await this.leagueMembershipRepository.getJoinRequests(input.leagueId);
    const request = requests.find((r) => r.id === input.joinRequestId);
    if (!request) {
      return Result.err({ code: 'JOIN_REQUEST_NOT_FOUND' });
    }

    await this.leagueMembershipRepository.removeJoinRequest(input.joinRequestId);

    output.present({ success: true, message: 'Join request rejected.' });
    return Result.ok(undefined);
  }
}