import type { CompetitionFactView, CompetitionFactsResponse, TeamCompetitionViewResponse, } from '@lolympus/contracts'; import { ConflictException, ForbiddenException, Injectable, NotFoundException, UnprocessableEntityException, } from '@nestjs/common'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import type { Competition, CompetitionFact } from './competition.schema'; type PersistenceId = string | mongoose.Types.ObjectId; type CompetitionRecord = Competition & { _id: mongoose.Types.ObjectId }; export interface CompetitionScope { communityId: mongoose.Types.ObjectId; matchId: mongoose.Types.ObjectId; } /** * A team view is addressed either by the caller's membership (signed-in) or by * an explicit team id. The explicit form exists so that the team progress page * stays usable while community members have not all signed in yet. */ export type TeamViewScope = CompetitionScope & ( | { userId: mongoose.Types.ObjectId; teamId?: undefined } | { teamId: mongoose.Types.ObjectId; userId?: undefined } ); interface CompetitionProjectionSource { series?: Array>; gameSlots?: Array>; } @Injectable() export class CompetitionQueryService { constructor(private readonly connectionService: ConnectionService) {} /** Resolve the aggregate created by the finalized team-build workflow. */ public async getCompetition( scope: CompetitionScope, ): Promise { const MatchModel = await this.connectionService.getModel('match'); const match = await MatchModel.findOne({ _id: scope.matchId, communityId: scope.communityId, }) .lean() .exec(); if (!match) throw new NotFoundException('Match not found.'); if ( match.status === 'recruiting' || !Array.isArray(match.teams) || match.teams.length < 2 ) { throw new ConflictException( 'Competition is unavailable until team building is complete.', ); } const CompetitionModel = await this.connectionService.getModel('competition'); const existing = await CompetitionModel.findOne({ matchId: scope.matchId, communityId: scope.communityId, }) .lean() .exec(); if (existing) return existing as CompetitionRecord; throw new ConflictException( 'Competition is still being initialized by the team-build workflow.', ); } public async getTeamView( scope: TeamViewScope, ): Promise { const competition = (await this.getCompetition(scope)) as Competition & { _id: PersistenceId; }; const requestedTeamId = scope.teamId; const team = requestedTeamId ? competition.teams.find(({ teamId }) => sameId(teamId, requestedTeamId)) : competition.teams.find(({ members }) => members.some(({ userId }) => sameId(userId, scope.userId)), ); if (!team) { if (requestedTeamId) { throw new NotFoundException('Competition team not found.'); } throw new ForbiddenException( 'Only a Competition team member may access the team view.', ); } const projection = competition.projection as CompetitionProjectionSource; const allSeries = Array.isArray(projection.series) ? projection.series : []; const teamId = idString(team.teamId); const activeSeries = allSeries.filter( (series) => series.status !== 'completed' && series.status !== 'inactive' && Array.isArray(series.entries) && series.entries.some( (entry) => isRecord(entry) && idString(entry.teamId as PersistenceId) === teamId, ), ); const activeSeriesIds = new Set( activeSeries.map((series) => idString(series.seriesId as PersistenceId)), ); const gameSlots = ( Array.isArray(projection.gameSlots) ? projection.gameSlots : [] ).filter((slot) => activeSeriesIds.has(idString(slot.seriesId as PersistenceId)), ); const AssignmentModel = await this.connectionService.getModel( 'tournamentCodeAssignment', ); const queriedAssignments = await AssignmentModel.find({ competitionId: competition._id, seriesId: { $in: [...activeSeriesIds] }, state: { $in: ['reserved', 'used'] }, }) .lean() .exec(); // Keep this defensive filter even when the persistence query is mocked or // changed: an opponent-only assignment must never cross this boundary. const assignments = queriedAssignments.filter((assignment) => activeSeriesIds.has(idString(assignment.seriesId)), ); const codeIds = assignments.map(({ tournamentCodeId }) => tournamentCodeId); const TournamentCodeModel = await this.connectionService.getModel('tournamentCode'); const codes = codeIds.length ? await TournamentCodeModel.find({ _id: { $in: codeIds }, state: { $in: ['reserved', 'used'] }, }) .lean() .exec() : []; const codeById = new Map(codes.map((code) => [idString(code._id), code])); const assignmentBySlot = new Map( assignments.map((assignment) => [ idString(assignment.gameSlotId), assignment, ]), ); return { competitionId: idString(competition._id) as never, revision: competition.revision, phase: competition.phase, teamId: teamId as never, activeSeries: toWire(activeSeries) as never, tournamentCodes: gameSlots.map((slot) => { const gameSlotId = idString(slot.id as PersistenceId); const assignment = assignmentBySlot.get(gameSlotId); const code = assignment ? codeById.get(idString(assignment.tournamentCodeId)) : undefined; if ( assignment && (!code || code.state !== assignment.state || !code.matchId || !sameId(code.matchId, competition.matchId)) ) { throw new ConflictException( 'Tournament Code assignment is inconsistent and cannot be exposed.', ); } return { gameSlotId: gameSlotId as never, seriesId: idString(slot.seriesId as PersistenceId) as never, ordinal: numberValue(slot.ordinal), displayNumber: numberValue(slot.displayNumber), state: assignment?.state === 'reserved' || assignment?.state === 'used' ? assignment.state : 'pending', code: typeof code?.code === 'string' ? code.code : null, expiresAt: code?.expiresAt ? isoDate(code.expiresAt) : null, }; }), }; } public async listFacts( scope: CompetitionScope & { cursor?: string; limit?: number }, ): Promise { const competition = (await this.getCompetition(scope)) as Competition & { _id: PersistenceId; }; const limit = normalizeLimit(scope.limit); const cursor = scope.cursor ? decodeCursor(scope.cursor) : undefined; const cursorFilter = cursor ? { $or: [ { revision: { $gt: cursor.revision } }, { revision: cursor.revision, ordinalWithinRevision: { $gt: cursor.ordinalWithinRevision }, }, { revision: cursor.revision, ordinalWithinRevision: cursor.ordinalWithinRevision, _id: { $gt: new mongoose.Types.ObjectId(cursor.id) }, }, ], } : {}; const FactModel = await this.connectionService.getModel('competitionFact'); const rows = await FactModel.find({ competitionId: competition._id, ...cursorFilter, }) .sort({ revision: 1, ordinalWithinRevision: 1, _id: 1 }) .limit(limit + 1) .lean() .exec(); const page = rows.slice(0, limit); const last = page.at(-1); return { facts: page.map(presentFact), nextCursor: rows.length > limit && last ? encodeCursor({ revision: requiredNumber(last.revision, 'revision'), ordinalWithinRevision: requiredNumber( last.ordinalWithinRevision, 'ordinalWithinRevision', ), id: requiredId(last._id, '_id'), }) : null, }; } } function presentFact( source: CompetitionFact & { _id: mongoose.Types.ObjectId }, ): CompetitionFactView { const common = { id: requiredId(source._id, '_id') as never, competitionId: requiredId(source.competitionId, 'competitionId') as never, revision: requiredNumber(source.revision, 'revision'), ordinalWithinRevision: requiredNumber( source.ordinalWithinRevision, 'ordinalWithinRevision', ), commandId: requiredString(source.commandId, 'commandId') as never, schemaVersion: requiredNumber(source.schemaVersion, 'schemaVersion'), actor: toWire(source.actor) as never, occurredAt: isoDate(source.occurredAt), recordedAt: isoDate(source.recordedAt), ...(typeof source.causationId === 'string' && source.causationId.length > 0 ? { causationId: source.causationId } : {}), }; switch (source.type) { case 'game-accepted': return { ...common, type: 'game-accepted', gameId: requiredId(source.gameId, 'gameId') as never, seriesId: requiredId(source.seriesId, 'seriesId') as never, gameSlotId: requiredId(source.gameSlotId, 'gameSlotId') as never, ordinal: requiredNumber(source.ordinal, 'ordinal'), startedAt: isoDate(source.startedAt ?? source.occurredAt), durationSeconds: numberValue(source.durationSeconds ?? 0), participants: toWire(source.participants ?? []) as never, evidence: toWire(source.evidence) as never, mapping: toWire(source.mapping) as never, }; case 'game-voided': return { ...common, type: 'game-voided', gameAcceptedFactId: requiredId( source.gameAcceptedFactId, 'gameAcceptedFactId', ) as never, reason: requiredString(source.reason, 'reason'), }; case 'series-adjudicated': return { ...common, type: 'series-adjudicated', seriesId: requiredId(source.seriesId, 'seriesId') as never, decision: toWire(source.decision) as never, reason: requiredString(source.reason, 'reason'), }; case 'adjudication-reversed': return { ...common, type: 'adjudication-reversed', adjudicationFactId: requiredId( source.adjudicationFactId, 'adjudicationFactId', ) as never, reason: requiredString(source.reason, 'reason'), }; default: throw new Error('Unsupported Competition fact type.'); } } interface FactCursor { revision: number; ordinalWithinRevision: number; id: string; } function encodeCursor(cursor: FactCursor): string { return Buffer.from(JSON.stringify(cursor)).toString('base64url'); } function decodeCursor(value: string): FactCursor { try { const parsed: unknown = JSON.parse( Buffer.from(value, 'base64url').toString('utf8'), ); if ( !isRecord(parsed) || !Number.isInteger(parsed.revision) || !Number.isInteger(parsed.ordinalWithinRevision) || typeof parsed.id !== 'string' || !mongoose.isValidObjectId(parsed.id) ) { throw new Error('malformed cursor'); } return parsed as unknown as FactCursor; } catch { throw new UnprocessableEntityException('Invalid facts cursor.'); } } function normalizeLimit(value: number | undefined): number { if (value === undefined) return 50; if (!Number.isInteger(value) || value < 1 || value > 100) { throw new UnprocessableEntityException( 'Facts page limit must be an integer from 1 through 100.', ); } return value; } function sameId(left: PersistenceId, right: PersistenceId): boolean { return idString(left) === idString(right); } function idString(value: PersistenceId): string { return value instanceof mongoose.Types.ObjectId ? value.toHexString() : String(value); } function isoDate(value: unknown): string { if (value instanceof Date) return value.toISOString(); if (typeof value === 'string') return value; throw new Error('Competition fact contains an invalid date.'); } function numberValue(value: unknown): number { return typeof value === 'number' ? value : Number(value); } function toWire(value: unknown): unknown { if (value instanceof mongoose.Types.ObjectId) return value.toHexString(); if (value instanceof Date) return value.toISOString(); if (Array.isArray(value)) return value.map(toWire); if (isRecord(value)) { return Object.fromEntries( Object.entries(value).map(([key, child]) => [key, toWire(child)]), ); } return value; } function isRecord(value: unknown): value is Record { return value !== null && typeof value === 'object' && !Array.isArray(value); } function requiredId(value: unknown, field: string): string { if (value instanceof mongoose.Types.ObjectId) return value.toHexString(); return requiredString(value, field); } function requiredString(value: unknown, field: string): string { if (typeof value === 'string' && value.length > 0) return value; throw new Error(`Competition fact contains an invalid ${field}.`); } function requiredNumber(value: unknown, field: string): number { if (typeof value === 'number' && Number.isFinite(value)) return value; throw new Error(`Competition fact contains an invalid ${field}.`); }