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

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

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

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

  async execute(
    input: RejectLeagueJoinRequestInput,
  ): Promise<
    Result<
      RejectLeagueJoinRequestResult,
      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);

    const result: RejectLeagueJoinRequestResult = { success: true, message: 'Join request rejected.' };
    return Result.ok(result);
  }
}