Files
gridpilot.gg/core/racing/application/use-cases/GetAllLeaguesWithCapacityUseCase.ts
2025-12-21 17:05:36 +01:00

76 lines
2.5 KiB
TypeScript

import type { ILeagueRepository } from '../../domain/repositories/ILeagueRepository';
import type { ILeagueMembershipRepository } from '../../domain/repositories/ILeagueMembershipRepository';
import type { League } from '../../domain/entities/League';
import { Result } from '@core/shared/application/Result';
import type { ApplicationErrorCode } from '@core/shared/errors/ApplicationErrorCode';
import type { UseCaseOutputPort } from '@core/shared/application/UseCaseOutputPort';
export type GetAllLeaguesWithCapacityInput = {};
export type LeagueCapacitySummary = {
league: League;
currentDrivers: number;
maxDrivers: number;
};
export type GetAllLeaguesWithCapacityResult = {
leagues: LeagueCapacitySummary[];
};
export type GetAllLeaguesWithCapacityErrorCode = 'REPOSITORY_ERROR';
/**
* Use Case for retrieving all leagues with capacity information.
* Orchestrates domain logic and delegates presentation to an output port.
*/
export class GetAllLeaguesWithCapacityUseCase {
constructor(
private readonly leagueRepository: ILeagueRepository,
private readonly leagueMembershipRepository: ILeagueMembershipRepository,
private readonly outputPort: UseCaseOutputPort<GetAllLeaguesWithCapacityResult, GetAllLeaguesWithCapacityErrorCode>,
) {}
async execute(
_input: GetAllLeaguesWithCapacityInput = {},
): Promise<
Result<
GetAllLeaguesWithCapacityResult,
ApplicationErrorCode<GetAllLeaguesWithCapacityErrorCode, { message: string }>
>
> {
try {
const leagues = await this.leagueRepository.findAll();
const summaries: LeagueCapacitySummary[] = [];
for (const league of leagues) {
const members = await this.leagueMembershipRepository.getLeagueMembers(league.id.toString());
const currentDrivers = members.filter(
(m) =>
m.status.toString() === 'active' &&
(m.role.toString() === 'owner' ||
m.role.toString() === 'admin' ||
m.role.toString() === 'steward' ||
m.role.toString() === 'member'),
).length;
const maxDrivers = league.settings.maxDrivers ?? 0;
summaries.push({ league, currentDrivers, maxDrivers });
}
return Result.ok({ leagues: summaries });
} catch (error: unknown) {
const message =
error instanceof Error && error.message
? error.message
: 'Failed to load leagues with capacity';
return Result.err({
code: 'REPOSITORY_ERROR',
details: { message },
});
}
}
}