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

export interface UpdateLeagueMemberRoleUseCaseParams {
  leagueId: string;
  targetDriverId: string;
  newRole: string;
}

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

  async execute(params: UpdateLeagueMemberRoleUseCaseParams): Promise<Result<void, ApplicationErrorCode<'MEMBERSHIP_NOT_FOUND'>>> {
    const memberships = await this.leagueMembershipRepository.getLeagueMembers(params.leagueId);
    const membership = memberships.find(m => m.driverId === params.targetDriverId);
    if (!membership) {
      return Result.err({ code: 'MEMBERSHIP_NOT_FOUND' });
    }
    await this.leagueMembershipRepository.saveMembership({
      ...membership,
      role: params.newRole,
    });
    return Result.ok(undefined);
  }
}