diff --git a/apps/api/src/modules/global/database/migrations/20260712-competition-domain.spec.ts b/apps/api/src/modules/global/database/migrations/20260712-competition-domain.spec.ts new file mode 100644 index 00000000..46758d13 --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/20260712-competition-domain.spec.ts @@ -0,0 +1,303 @@ +import { projectCompetition } from '../../../competition/domain/competition-projector'; +import { + planCompetitionMigration, + type LegacyMatchInput, + type ReadyCompetitionMigrationPlan, +} from './20260712-competition-domain'; + +describe('planCompetitionMigration', () => { + it('produces deterministic, idempotent identities and maps legacy bracket mode explicitly', () => { + const legacy = pairedMatch({ gameMode: 'bracket' }); + + const first = planCompetitionMigration(legacy); + const second = planCompetitionMigration(structuredClone(legacy)); + + expect(first).toEqual(second); + const plan = requireReady(first); + expect(plan.competition.id).toMatch(/^[a-f0-9]{24}$/); + expect(plan.competition.teams.map((team) => team.teamId)).toEqual( + expect.arrayContaining([ + expect.stringMatching(/^[a-f0-9]{24}$/), + expect.stringMatching(/^[a-f0-9]{24}$/), + ]), + ); + expect(plan.competition.format).toMatchObject({ type: 'paired-series' }); + expect(plan.warnings).toContainEqual( + expect.objectContaining({ + code: 'LEGACY_BRACKET_MAPPED_TO_PAIRED_SERIES', + }), + ); + }); + + it('preserves Riot-backed and normalized-only games as different evidence kinds', () => { + const legacy = pairedMatch({ gameCount: 2 }); + legacy.result = { + games: [ + legacyGame({ + gameNumber: 1, + riotMatchId: 'KR_WITH_ARCHIVE', + blueTeamIndex: 1, + redTeamIndex: 2, + winnerTeamIndex: 1, + riotArchivePresent: true, + }), + legacyGame({ + gameNumber: 2, + riotMatchId: 'KR_NORMALIZED_ONLY', + blueTeamIndex: 2, + redTeamIndex: 1, + winnerTeamIndex: 2, + riotArchivePresent: false, + }), + ], + seriesResults: [], + }; + + const plan = requireReady(planCompetitionMigration(legacy)); + const games = plan.facts.filter((fact) => fact.type === 'game-accepted'); + + expect(games).toHaveLength(2); + expect(games[0]).toMatchObject({ + evidence: { + type: 'riot', + riotMatchId: 'KR_WITH_ARCHIVE', + }, + }); + expect(games[1]).toMatchObject({ + evidence: { + type: 'legacy', + legacyReference: expect.stringContaining('KR_NORMALIZED_ONLY'), + }, + }); + }); + + it('turns a winner-only Series into an adjudication without fabricating games', () => { + const legacy = pairedMatch({ gameCount: 3 }); + legacy.result = { + games: [], + seriesResults: [ + { + teamAIndex: 1, + teamBIndex: 2, + teamAWins: 0, + teamBWins: 0, + winnerTeamIndex: 2, + }, + ], + }; + + const plan = requireReady(planCompetitionMigration(legacy)); + + expect(plan.facts).toHaveLength(1); + expect(plan.facts[0]).toMatchObject({ + type: 'series-adjudicated', + decision: { + type: 'administrative', + winnerTeamId: plan.competition.teams[1].teamId, + }, + reason: 'legacy-winner-only-result', + }); + expect(plan.facts).not.toContainEqual( + expect.objectContaining({ type: 'game-accepted' }), + ); + }); + + it('quarantines an ambiguous legacy game assignment instead of guessing', () => { + const legacy = pairedMatch({ + teams: [ + legacyTeam(1, 'One'), + legacyTeam(2, 'Two'), + legacyTeam(3, 'Three'), + legacyTeam(4, 'Four'), + ], + }); + legacy.gameSchedule = [ + { gameNumber: 7, teamAIndex: 1, teamBIndex: 2 }, + { gameNumber: 7, teamAIndex: 3, teamBIndex: 4 }, + ]; + legacy.result = { + games: [ + legacyGame({ + gameNumber: 7, + riotMatchId: 'KR_AMBIGUOUS', + blueTeamIndex: 1, + redTeamIndex: 2, + winnerTeamIndex: 1, + riotArchivePresent: true, + }), + ], + seriesResults: [], + }; + + const plan = planCompetitionMigration(legacy); + + expect(plan).toMatchObject({ + status: 'quarantined', + reasons: expect.arrayContaining([ + expect.objectContaining({ code: 'AMBIGUOUS_GAME_ASSIGNMENT' }), + ]), + }); + }); + + it('repairs the data.txt WB_R2_M2 positional bug from accepted game evidence', () => { + const legacy = loadDataTxtFixture(); + + const plan = requireReady(planCompetitionMigration(legacy)); + const projection = projectCompetition({ + competitionId: plan.competition.id, + revision: plan.competition.revision, + projectorVersion: plan.competition.projectorVersion, + teams: plan.competition.teams, + format: plan.competition.format, + seriesGraph: plan.competition.seriesGraph, + facts: plan.facts, + }); + const team3 = plan.competition.teams.find( + (team) => team.legacyTeamIndex === 3, + ); + const team8 = plan.competition.teams.find( + (team) => team.legacyTeamIndex === 8, + ); + const series = (code: string) => + projection.series.find((candidate) => candidate.code === code); + + expect(team3).toBeDefined(); + expect(team8).toBeDefined(); + expect(series('WB_R2_M2')).toMatchObject({ + status: 'completed', + entries: [ + { slot: 'A', teamId: team8!.teamId, gameWins: 2 }, + { slot: 'B', teamId: team3!.teamId, gameWins: 1 }, + ], + outcome: { + type: 'played', + winnerTeamId: team8!.teamId, + loserTeamId: team3!.teamId, + }, + }); + expect(series('WB_FINAL')).toMatchObject({ + entries: expect.arrayContaining([ + { slot: 'B', teamId: team8!.teamId, gameWins: 0 }, + ]), + }); + expect(series('LB_R2_M1')).toMatchObject({ + entries: expect.arrayContaining([ + { slot: 'B', teamId: team3!.teamId, gameWins: 0 }, + ]), + }); + }); +}); + +function pairedMatch( + overrides: Partial = {}, +): LegacyMatchInput { + return { + _id: 'match-legacy-paired', + communityId: 'community-1', + gameMode: 'pair', + gameCount: 1, + status: 'in-progress', + teams: [legacyTeam(1, 'One'), legacyTeam(2, 'Two')], + gameSchedule: [{ gameNumber: 1, teamAIndex: 1, teamBIndex: 2 }], + createdAt: '2026-07-01T00:00:00.000Z', + updatedAt: '2026-07-02T00:00:00.000Z', + ...overrides, + }; +} + +function legacyTeam(teamIndex: number, name: string) { + return { + teamIndex, + name, + captainUserId: `captain-${teamIndex}`, + members: [], + }; +} + +function legacyGame( + overrides: Partial['games'][number]>, +): NonNullable['games'][number] { + return { + gameNumber: 1, + riotMatchId: 'KR_DEFAULT', + blueTeamIndex: 1, + redTeamIndex: 2, + winnerTeamIndex: 1, + gameCreation: 1782864000000, + gameDuration: 1800, + participants: [], + ...overrides, + }; +} + +function requireReady( + plan: ReturnType, +): ReadyCompetitionMigrationPlan { + if (plan.status !== 'ready') { + throw new Error( + `Expected ready migration plan: ${JSON.stringify(plan.reasons)}`, + ); + } + return plan; +} + +function loadDataTxtFixture(): LegacyMatchInput { + const seededTeamIndexes = [1, 8, 3, 4, 5, 6, 7, 2]; + const games = [ + ['WB_R1_M3', 8, 7, 8], + ['WB_R1_M3', 7, 8, 8], + ['WB_R1_M4', 3, 6, 3], + ['WB_R1_M4', 6, 3, 3], + ['WB_R2_M2', 3, 8, 8], + ['WB_R2_M2', 8, 3, 3], + ['WB_R2_M2', 3, 8, 8], + ] as const; + + return { + _id: '6a3e0c2c8ade90b14b72f335', + communityId: '69ebe0adf627c11be2f020a1', + gameMode: 'double-elimination', + gameCount: 3, + status: 'in-progress', + teams: Array.from({ length: 8 }, (_, index) => + legacyTeam( + index + 1, + index + 1 === 3 + ? '해온해줘' + : index + 1 === 8 + ? '똥칼라파워' + : `${index + 1}팀`, + ), + ), + doubleElimination: { + teamCount: 8, + resetFinalEnabled: true, + seeds: seededTeamIndexes.map((teamIndex, index) => ({ + seedNumber: index + 1, + teamIndex, + })), + bracketMatches: [], + }, + result: { + games: games.map( + ( + [bracketMatchId, blueTeamIndex, redTeamIndex, winnerTeamIndex], + index, + ) => + legacyGame({ + gameNumber: index + 1, + bracketMatchId, + riotMatchId: `KR_DATA_TXT_${index + 1}`, + riotArchivePresent: true, + blueTeamIndex, + redTeamIndex, + winnerTeamIndex, + gameCreation: 1782864000000 + index * 60_000, + }), + ), + seriesResults: [], + }, + createdAt: '2026-06-27T05:18:00.000Z', + updatedAt: '2026-07-12T17:17:00.000Z', + }; +} diff --git a/apps/api/src/modules/global/database/migrations/20260712-competition-domain.ts b/apps/api/src/modules/global/database/migrations/20260712-competition-domain.ts new file mode 100644 index 00000000..1c9a2f0f --- /dev/null +++ b/apps/api/src/modules/global/database/migrations/20260712-competition-domain.ts @@ -0,0 +1,1480 @@ +import { createHash } from 'node:crypto'; +import { projectCompetition } from '../../../competition/domain/competition-projector'; +import { + generateSeriesGraph, + type CompetitionGraphFormat, + type SeriesDefinition, +} from '../../../competition/domain/series-graph'; + +const MIGRATION_RUN_ID = '20260712-competition-domain'; +const SCHEMA_VERSION = 1; +const PROJECTOR_VERSION = 1; +const EPOCH = '1970-01-01T00:00:00.000Z'; + +type LegacyGameMode = 'pair' | 'bracket' | 'round-robin' | 'double-elimination'; + +interface LegacyTeamMemberInput { + userId: unknown; + assignedPosition?: string; + cost?: number; +} + +interface LegacyTeamInput { + teamIndex: number; + name?: string; + captainUserId?: unknown; + members?: LegacyTeamMemberInput[]; +} + +interface LegacyParticipantInput { + userId: unknown; + gameName?: string; + tagLine?: string; + profileIconId?: number; +} + +interface LegacyGameInput { + gameNumber: number; + bracketMatchId?: string; + riotMatchId?: string; + riotArchivePresent?: boolean; + payloadHash?: string; + blueTeamIndex: number; + redTeamIndex: number; + winnerTeamIndex: number; + winnerSide?: 'blue' | 'red'; + gameCreation?: number | string | Date; + gameDuration?: number; + participants?: Array<{ + userId?: unknown; + teamIndex?: number; + side?: 'blue' | 'red'; + [key: string]: unknown; + }>; +} + +interface LegacySeriesResultInput { + bracketMatchId?: string; + teamAIndex: number; + teamBIndex: number; + teamAWins?: number; + teamBWins?: number; + winnerTeamIndex?: number; +} + +interface LegacyBracketMatchInput { + bracketMatchId: string; + gameNumber?: number; + gameCount?: number; + requiredWins?: number; + bracketSide?: 'winner' | 'loser' | 'grand-final' | 'reset-final'; + state?: 'pending' | 'ready' | 'completed'; + winnerTeamIndex?: number; + completedAt?: Date | string; + completedBy?: 'riot-result' | 'walkover'; + walkover?: { + winnerTeamIndex: number; + reason?: string; + awardedBy?: unknown; + awardedAt?: Date | string; + active: boolean; + }; +} + +interface LegacyTournamentCodeInput { + _id: unknown; + state?: 'available' | 'reserved' | 'used' | 'expired' | 'released' | 'voided'; + gameNumber?: number; + bracketMatchId?: string; + riotMatchId?: string; + reservedAt?: Date | string; + usedAt?: Date | string; + releasedAt?: Date | string; +} + +export interface LegacyMatchInput { + _id: unknown; + communityId: unknown; + gameMode: LegacyGameMode; + gameCount: number; + roundRobinMaxRounds?: number; + status?: string; + participants?: LegacyParticipantInput[]; + teams: LegacyTeamInput[]; + gameSchedule?: Array<{ + gameNumber: number; + roundNumber?: number; + teamAIndex: number; + teamBIndex: number; + }>; + result?: { + winnerTeamIndex?: number; + riotMatchIds?: string[]; + games: LegacyGameInput[]; + seriesResults?: LegacySeriesResultInput[]; + }; + doubleElimination?: { + teamCount?: 4 | 8; + resetFinalEnabled?: boolean; + seeds?: Array<{ seedNumber: number; teamIndex: number }>; + bracketMatches?: LegacyBracketMatchInput[]; + }; + tournamentCodes?: LegacyTournamentCodeInput[]; + riotMatchArchiveIds?: string[]; + createdAt?: Date | string; + updatedAt?: Date | string; +} + +export interface CompetitionMigrationIssue { + code: string; + message: string; + details?: Record; +} + +export interface CompetitionMigrationTeamSnapshot { + teamId: string; + legacyTeamIndex: number; + displayOrder: number; + seedNumber: number; + name: string; + captainUserId?: string; + members: Array<{ + userId: string; + displayName: string; + gameName?: string; + tagLine?: string; + profileIconId?: number; + assignedPosition?: string; + cost?: number; + }>; +} + +interface MigrationFactBase { + id: string; + competitionId: string; + revision: number; + ordinalWithinRevision: 1; + commandId: string; + idempotencyKey: string; + requestHash: string; + schemaVersion: 1; + actor: { type: 'migration'; migrationRunId: string }; + occurredAt: string; + recordedAt: string; +} + +export interface MigrationGameAcceptedFact extends MigrationFactBase { + type: 'game-accepted'; + gameId: string; + seriesId: string; + gameSlotId: string; + ordinal: number; + evidence: + | { type: 'riot'; riotMatchId: string; payloadHash: string } + | { type: 'legacy'; legacyReference: string }; + mapping: { + mappingVersion: 1; + confidence: number; + blueTeamId: string; + redTeamId: string; + winnerTeamId: string; + participantAssignments: Array<{ + userId: string; + teamId: string; + side: 'blue' | 'red'; + }>; + }; +} + +export interface MigrationSeriesAdjudicatedFact extends MigrationFactBase { + type: 'series-adjudicated'; + seriesId: string; + decision: + | { + type: 'walkover' | 'administrative'; + winnerTeamId: string; + } + | { type: 'administrative-draw' }; + reason: string; +} + +export type CompetitionMigrationFact = + | MigrationGameAcceptedFact + | MigrationSeriesAdjudicatedFact; + +export interface CompetitionMigrationAssignment { + id: string; + competitionId: string; + seriesId: string; + gameSlotId: string; + tournamentCodeId: string; + state: 'reserved' | 'used' | 'released' | 'voided'; + reservedAt: string; + usedAt?: string; + releasedAt?: string; + riotMatchId?: string; + commandId: string; +} + +export interface CompetitionMigrationSnapshot { + id: string; + matchId: string; + communityId: string; + schemaVersion: 1; + projectorVersion: 1; + revision: number; + phase: 'ready' | 'running' | 'completed' | 'cancelled'; + teams: CompetitionMigrationTeamSnapshot[]; + format: CompetitionGraphFormat; + seriesGraph: SeriesDefinition[]; + projection: ReturnType; + createdAt: string; + updatedAt: string; +} + +export interface ReadyCompetitionMigrationPlan { + status: 'ready'; + competition: CompetitionMigrationSnapshot; + facts: CompetitionMigrationFact[]; + assignments: CompetitionMigrationAssignment[]; + warnings: CompetitionMigrationIssue[]; +} + +export interface QuarantinedCompetitionMigrationPlan { + status: 'quarantined'; + matchId: string; + reasons: CompetitionMigrationIssue[]; + warnings: CompetitionMigrationIssue[]; +} + +export type CompetitionMigrationPlan = + | ReadyCompetitionMigrationPlan + | QuarantinedCompetitionMigrationPlan; + +interface PlannedGame { + legacy: LegacyGameInput; + series: SeriesDefinition; + confidence: number; + ordinal: number; +} + +interface PendingFact { + kind: CompetitionMigrationFact['type']; + seriesOrder: number; + occurredAt: string; + logicalKey: string; + build(base: MigrationFactBase): CompetitionMigrationFact; +} + +/** + * Builds an entirely deterministic write plan from one legacy Match snapshot. + * It performs no I/O and deliberately quarantines uncertainty instead of + * guessing a Series or team identity. + */ +export function planCompetitionMigration( + input: LegacyMatchInput, + options: { migrationRunId?: string } = {}, +): CompetitionMigrationPlan { + const migrationRunId = options.migrationRunId ?? MIGRATION_RUN_ID; + const warnings: CompetitionMigrationIssue[] = []; + const reasons: CompetitionMigrationIssue[] = []; + const matchId = opaqueString(input?._id); + const communityId = opaqueString(input?.communityId); + + if (!matchId) { + reasons.push( + issue('MATCH_ID_MISSING', 'The legacy Match has no identity.'), + ); + } + if (!communityId) { + reasons.push( + issue( + 'COMMUNITY_ID_MISSING', + 'The legacy Match has no Community identity.', + ), + ); + } + + const competitionId = stableId(matchId || 'missing-match', 'competition'); + const teamBuild = buildTeamSnapshots(input, competitionId, reasons); + if (reasons.length > 0) { + return quarantined(matchId, reasons, warnings); + } + + const format = buildFormat(input, warnings, reasons); + if (!format) return quarantined(matchId, reasons, warnings); + + let seriesGraph: SeriesDefinition[]; + try { + seriesGraph = generateSeriesGraph({ + competitionId, + teams: teamBuild.teams, + format, + }); + } catch (error) { + reasons.push( + issue( + 'SERIES_GRAPH_GENERATION_FAILED', + errorMessage(error), + errorCodeDetails(error), + ), + ); + return quarantined(matchId, reasons, warnings); + } + + const plannedGames = mapGames( + input, + seriesGraph, + teamBuild.teamIdByLegacyIndex, + reasons, + ); + const pendingFacts: PendingFact[] = []; + addGameFacts( + input, + competitionId, + plannedGames, + teamBuild.teamIdByLegacyIndex, + seriesGraph, + pendingFacts, + reasons, + ); + addAdjudicationFacts( + input, + competitionId, + plannedGames, + teamBuild.teamIdByLegacyIndex, + seriesGraph, + pendingFacts, + reasons, + ); + if (reasons.length > 0) { + return quarantined(matchId, reasons, warnings); + } + + const facts = materializeFacts( + competitionId, + migrationRunId, + normalizeDate(input.updatedAt, normalizeDate(input.createdAt, EPOCH)), + pendingFacts, + ); + + let projection: ReturnType; + try { + projection = projectCompetition({ + competitionId, + revision: facts.length, + projectorVersion: PROJECTOR_VERSION, + teams: teamBuild.teams, + format, + seriesGraph, + facts, + }); + } catch (error) { + reasons.push( + issue( + 'MIGRATION_PROJECTION_REJECTED', + errorMessage(error), + errorCodeDetails(error), + ), + ); + return quarantined(matchId, reasons, warnings); + } + + const assignments = buildAssignments( + input, + competitionId, + plannedGames, + facts, + seriesGraph, + warnings, + reasons, + ); + if (reasons.length > 0) { + return quarantined(matchId, reasons, warnings); + } + + const createdAt = normalizeDate(input.createdAt, EPOCH); + const updatedAt = normalizeDate(input.updatedAt, createdAt); + return { + status: 'ready', + competition: { + id: competitionId, + matchId, + communityId, + schemaVersion: SCHEMA_VERSION, + projectorVersion: PROJECTOR_VERSION, + revision: facts.length, + phase: projection.phase, + teams: teamBuild.teams, + format, + seriesGraph, + projection, + createdAt, + updatedAt, + }, + facts, + assignments, + warnings: sortedIssues(warnings), + }; +} + +function buildTeamSnapshots( + input: LegacyMatchInput, + competitionId: string, + reasons: CompetitionMigrationIssue[], +): { + teams: CompetitionMigrationTeamSnapshot[]; + teamIdByLegacyIndex: Map; +} { + const legacyTeams = Array.isArray(input?.teams) ? input.teams : []; + if (legacyTeams.length < 2) { + reasons.push( + issue('TEAMS_MISSING', 'At least two legacy teams are required.'), + ); + } + + const indexes = new Set(); + for (const team of legacyTeams) { + if (!Number.isInteger(team.teamIndex) || team.teamIndex < 1) { + reasons.push( + issue('INVALID_LEGACY_TEAM_INDEX', 'A legacy team index is invalid.', { + teamIndex: team.teamIndex, + }), + ); + continue; + } + if (indexes.has(team.teamIndex)) { + reasons.push( + issue( + 'DUPLICATE_LEGACY_TEAM_INDEX', + `Legacy team index ${team.teamIndex} occurs more than once.`, + { teamIndex: team.teamIndex }, + ), + ); + } + indexes.add(team.teamIndex); + } + + const sorted = [...legacyTeams].sort( + (left, right) => left.teamIndex - right.teamIndex, + ); + const displayOrderByIndex = new Map( + sorted.map((team, index) => [team.teamIndex, index + 1]), + ); + const seedByTeamIndex = seedMap(input, sorted, reasons); + const participantByUserId = new Map( + (input.participants ?? []).map((participant) => [ + opaqueString(participant.userId), + participant, + ]), + ); + const teamIdByLegacyIndex = new Map(); + const teams = sorted.map((team) => { + const teamId = stableId(competitionId, 'team', team.teamIndex); + teamIdByLegacyIndex.set(team.teamIndex, teamId); + const members = (team.members ?? []).map((member) => { + const userId = opaqueString(member.userId); + const participant = participantByUserId.get(userId); + return { + userId, + displayName: + participant?.gameName || + (userId ? `legacy-user:${userId}` : 'legacy-user'), + ...(participant?.gameName ? { gameName: participant.gameName } : {}), + ...(participant?.tagLine ? { tagLine: participant.tagLine } : {}), + ...(typeof participant?.profileIconId === 'number' + ? { profileIconId: participant.profileIconId } + : {}), + ...(member.assignedPosition + ? { assignedPosition: member.assignedPosition } + : {}), + ...(typeof member.cost === 'number' ? { cost: member.cost } : {}), + }; + }); + const captainUserId = opaqueString(team.captainUserId); + return { + teamId, + legacyTeamIndex: team.teamIndex, + displayOrder: displayOrderByIndex.get(team.teamIndex)!, + seedNumber: seedByTeamIndex.get(team.teamIndex)!, + name: team.name?.trim() || `${team.teamIndex}팀`, + ...(captainUserId ? { captainUserId } : {}), + members, + }; + }); + + return { teams, teamIdByLegacyIndex }; +} + +function seedMap( + input: LegacyMatchInput, + sortedTeams: LegacyTeamInput[], + reasons: CompetitionMigrationIssue[], +): Map { + if (input.gameMode !== 'double-elimination') { + return new Map( + sortedTeams.map((team, index) => [team.teamIndex, index + 1]), + ); + } + + const seeds = input.doubleElimination?.seeds ?? []; + if (seeds.length !== sortedTeams.length) { + reasons.push( + issue( + 'INVALID_DOUBLE_ELIMINATION_SEEDS', + 'Every double-elimination team must have exactly one seed.', + ), + ); + } + const result = new Map(); + const seenSeeds = new Set(); + for (const seed of seeds) { + if ( + !Number.isInteger(seed.seedNumber) || + seed.seedNumber < 1 || + seenSeeds.has(seed.seedNumber) || + !sortedTeams.some((team) => team.teamIndex === seed.teamIndex) || + result.has(seed.teamIndex) + ) { + reasons.push( + issue( + 'INVALID_DOUBLE_ELIMINATION_SEEDS', + 'Double-elimination seeds are duplicate, non-contiguous, or reference an unknown team.', + { seedNumber: seed.seedNumber, teamIndex: seed.teamIndex }, + ), + ); + continue; + } + seenSeeds.add(seed.seedNumber); + result.set(seed.teamIndex, seed.seedNumber); + } + for (let seedNumber = 1; seedNumber <= sortedTeams.length; seedNumber += 1) { + if (!seenSeeds.has(seedNumber)) { + reasons.push( + issue( + 'INVALID_DOUBLE_ELIMINATION_SEEDS', + 'Double-elimination seeds must be contiguous from one.', + { missingSeedNumber: seedNumber }, + ), + ); + } + } + return result; +} + +function buildFormat( + input: LegacyMatchInput, + warnings: CompetitionMigrationIssue[], + reasons: CompetitionMigrationIssue[], +): CompetitionGraphFormat | undefined { + const gameCount = positiveInteger(input.gameCount); + if (!gameCount) { + reasons.push( + issue( + 'INVALID_GAME_COUNT', + 'Legacy gameCount must be a positive integer.', + ), + ); + return undefined; + } + + switch (input.gameMode) { + case 'pair': + return fixedFormat('paired-series', gameCount); + case 'bracket': + warnings.push( + issue( + 'LEGACY_BRACKET_MAPPED_TO_PAIRED_SERIES', + 'The unused legacy bracket mode was executed as paired Series and is migrated accordingly.', + ), + ); + return fixedFormat('paired-series', gameCount); + case 'round-robin': + return { + type: 'round-robin', + rule: fixedRule(gameCount), + ...(positiveInteger(input.roundRobinMaxRounds) + ? { maxRounds: input.roundRobinMaxRounds } + : {}), + tieBreakers: ['series-wins', 'game-diff', 'head-to-head'], + }; + case 'double-elimination': { + const teamCount = input.teams.length; + if (teamCount !== 4 && teamCount !== 8) { + reasons.push( + issue( + 'UNSUPPORTED_DOUBLE_ELIMINATION_TEAM_COUNT', + 'Only four- and eight-team double elimination can be migrated.', + { teamCount }, + ), + ); + return undefined; + } + const bracketMatches = input.doubleElimination?.bracketMatches ?? []; + return { + type: 'double-elimination', + teamCount, + resetFinalEnabled: input.doubleElimination?.resetFinalEnabled ?? false, + rules: { + upper: legacyFirstToRule(bracketMatches, 'winner', gameCount), + lower: legacyFirstToRule(bracketMatches, 'loser', 1), + grandFinal: legacyFirstToRule(bracketMatches, 'grand-final', 1), + resetFinal: legacyFirstToRule(bracketMatches, 'reset-final', 1), + }, + }; + } + default: + reasons.push( + issue( + 'UNSUPPORTED_LEGACY_GAME_MODE', + `Unsupported legacy game mode: ${String(input.gameMode)}`, + ), + ); + return undefined; + } +} + +function fixedFormat(type: 'paired-series', gameCount: number) { + return { type, rule: fixedRule(gameCount) } as const; +} + +function fixedRule(gameCount: number) { + return { + type: 'fixed-games' as const, + gameCount, + drawPolicy: 'allow' as const, + }; +} + +function legacyFirstToRule( + bracketMatches: LegacyBracketMatchInput[], + bracketSide: NonNullable, + fallbackGameCount: number, +) { + const matching = bracketMatches.filter( + (bracketMatch) => bracketMatch.bracketSide === bracketSide, + ); + const maxGames = Math.max( + ...matching.map( + (bracketMatch) => positiveInteger(bracketMatch.gameCount) ?? 0, + ), + fallbackGameCount, + ); + const configuredWins = matching + .map((bracketMatch) => positiveInteger(bracketMatch.requiredWins)) + .filter((value): value is number => value !== undefined); + const winsRequired = configuredWins[0] ?? Math.floor(maxGames / 2) + 1; + return { type: 'first-to' as const, winsRequired, maxGames }; +} + +function mapGames( + input: LegacyMatchInput, + graph: SeriesDefinition[], + teamIds: Map, + reasons: CompetitionMigrationIssue[], +): PlannedGame[] { + const mapped: Array> = []; + const games = input.result?.games ?? []; + for (const game of games) { + const blueTeamId = teamIds.get(game.blueTeamIndex); + const redTeamId = teamIds.get(game.redTeamIndex); + const winnerTeamId = teamIds.get(game.winnerTeamIndex); + if (!blueTeamId || !redTeamId || !winnerTeamId) { + reasons.push( + issue( + 'GAME_REFERENCES_UNKNOWN_TEAM', + `Legacy game ${game.gameNumber} references an unknown team.`, + { + gameNumber: game.gameNumber, + blueTeamIndex: game.blueTeamIndex, + redTeamIndex: game.redTeamIndex, + winnerTeamIndex: game.winnerTeamIndex, + }, + ), + ); + continue; + } + if ( + blueTeamId === redTeamId || + (winnerTeamId !== blueTeamId && winnerTeamId !== redTeamId) + ) { + reasons.push( + issue( + 'INCONSISTENT_GAME_TEAM_EVIDENCE', + `Legacy game ${game.gameNumber} has an invalid team or winner set.`, + { gameNumber: game.gameNumber }, + ), + ); + continue; + } + + const resolution = resolveGameSeries( + input, + graph, + game, + blueTeamId, + redTeamId, + ); + if ('issue' in resolution) { + reasons.push(resolution.issue); + continue; + } + mapped.push({ + legacy: game, + series: resolution.series, + confidence: resolution.confidence, + }); + } + + const grouped = new Map>>(); + for (const game of mapped) { + const group = grouped.get(game.series.id) ?? []; + group.push(game); + grouped.set(game.series.id, group); + } + + const result: PlannedGame[] = []; + for (const [seriesId, seriesGames] of grouped) { + seriesGames.sort(compareLegacyGames); + const series = graph.find((candidate) => candidate.id === seriesId)!; + if (seriesGames.length > series.gameSlots.length) { + reasons.push( + issue( + 'TOO_MANY_GAMES_FOR_SERIES', + `Series ${series.code ?? series.id} has more legacy games than stable slots.`, + { + seriesId, + gameCount: seriesGames.length, + slotCount: series.gameSlots.length, + }, + ), + ); + continue; + } + seriesGames.forEach((game, index) => + result.push({ ...game, ordinal: index + 1 }), + ); + } + return result.sort( + (left, right) => + graph.indexOf(left.series) - graph.indexOf(right.series) || + left.ordinal - right.ordinal, + ); +} + +function resolveGameSeries( + input: LegacyMatchInput, + graph: SeriesDefinition[], + game: LegacyGameInput, + blueTeamId: string, + redTeamId: string, +): + | { series: SeriesDefinition; confidence: number } + | { issue: CompetitionMigrationIssue } { + if (game.bracketMatchId) { + const series = graph.find( + (candidate) => candidate.code === game.bracketMatchId, + ); + return series + ? { series, confidence: 1 } + : { + issue: issue( + 'GAME_SERIES_MAPPING_NOT_FOUND', + `Legacy bracket code ${game.bracketMatchId} has no Series.`, + { + gameNumber: game.gameNumber, + bracketMatchId: game.bracketMatchId, + }, + ), + }; + } + + const assignments = (input.gameSchedule ?? []).filter( + (assignment) => assignment.gameNumber === game.gameNumber, + ); + if (assignments.length > 1) { + return { + issue: issue( + 'AMBIGUOUS_GAME_ASSIGNMENT', + `Legacy game number ${game.gameNumber} maps to multiple schedule entries.`, + { gameNumber: game.gameNumber, assignmentCount: assignments.length }, + ), + }; + } + if (assignments.length === 1) { + const assignment = assignments[0]; + const expected = new Set([assignment.teamAIndex, assignment.teamBIndex]); + if (!expected.has(game.blueTeamIndex) || !expected.has(game.redTeamIndex)) { + return { + issue: issue( + 'GAME_ASSIGNMENT_TEAM_MISMATCH', + `Legacy game ${game.gameNumber} conflicts with its schedule entry.`, + { gameNumber: game.gameNumber }, + ), + }; + } + } + + const candidates = graph.filter((series) => + staticSeriesHasTeamSet(series, blueTeamId, redTeamId), + ); + if (candidates.length === 1) { + return { + series: candidates[0], + confidence: assignments.length === 1 ? 0.95 : 0.8, + }; + } + return { + issue: issue( + candidates.length > 1 + ? 'AMBIGUOUS_GAME_SERIES_MAPPING' + : 'GAME_SERIES_MAPPING_NOT_FOUND', + candidates.length > 1 + ? `Legacy game ${game.gameNumber} matches multiple Series.` + : `Legacy game ${game.gameNumber} cannot be mapped to a Series.`, + { + gameNumber: game.gameNumber, + candidateSeriesIds: candidates.map((series) => series.id), + }, + ), + }; +} + +function staticSeriesHasTeamSet( + series: SeriesDefinition, + leftTeamId: string, + rightTeamId: string, +): boolean { + const sourceTeamIds = series.slots.map((slot) => + slot.source.type === 'team' ? slot.source.teamId : undefined, + ); + return ( + sourceTeamIds.every((teamId) => teamId !== undefined) && + new Set(sourceTeamIds).size === 2 && + sourceTeamIds.includes(leftTeamId) && + sourceTeamIds.includes(rightTeamId) + ); +} + +function addGameFacts( + input: LegacyMatchInput, + competitionId: string, + plannedGames: PlannedGame[], + teamIds: Map, + graph: SeriesDefinition[], + pending: PendingFact[], + reasons: CompetitionMigrationIssue[], +): void { + const riotIds = new Set(); + for (const planned of plannedGames) { + const game = planned.legacy; + const riotMatchId = game.riotMatchId?.trim(); + if (riotMatchId && riotIds.has(riotMatchId)) { + reasons.push( + issue( + 'DUPLICATE_RIOT_MATCH_EVIDENCE', + `Riot match ${riotMatchId} appears more than once.`, + { riotMatchId }, + ), + ); + continue; + } + if (riotMatchId) riotIds.add(riotMatchId); + + const slot = planned.series.gameSlots.find( + (candidate) => candidate.ordinal === planned.ordinal, + )!; + const blueTeamId = teamIds.get(game.blueTeamIndex)!; + const redTeamId = teamIds.get(game.redTeamIndex)!; + const winnerTeamId = teamIds.get(game.winnerTeamIndex)!; + const occurredAt = gameOccurrence(game, input); + const evidence = gameEvidence(input, competitionId, planned); + const logicalKey = `game:${planned.series.id}:${planned.ordinal}:${riotMatchId ?? game.gameNumber}`; + pending.push({ + kind: 'game-accepted', + seriesOrder: graph.indexOf(planned.series), + occurredAt, + logicalKey, + build: (base) => ({ + ...base, + type: 'game-accepted', + gameId: stableId( + competitionId, + 'game', + planned.series.id, + planned.ordinal, + riotMatchId ?? game.gameNumber, + ), + seriesId: planned.series.id, + gameSlotId: slot.id, + ordinal: planned.ordinal, + evidence, + mapping: { + mappingVersion: 1, + confidence: planned.confidence, + blueTeamId, + redTeamId, + winnerTeamId, + participantAssignments: (game.participants ?? []) + .filter( + (participant) => + opaqueString(participant.userId) && + (participant.side === 'blue' || participant.side === 'red') && + teamIds.has(participant.teamIndex ?? -1), + ) + .map((participant) => ({ + userId: opaqueString(participant.userId), + teamId: teamIds.get(participant.teamIndex!)!, + side: participant.side!, + })), + }, + }), + }); + } +} + +function gameEvidence( + input: LegacyMatchInput, + competitionId: string, + planned: PlannedGame, +): MigrationGameAcceptedFact['evidence'] { + const game = planned.legacy; + const riotMatchId = game.riotMatchId?.trim(); + const archiveKnown = + game.riotArchivePresent === true || + (riotMatchId !== undefined && + input.riotMatchArchiveIds?.includes(riotMatchId)); + if (riotMatchId && archiveKnown) { + return { + type: 'riot', + riotMatchId, + payloadHash: + game.payloadHash ?? `sha256:${stableHash(canonicalize(game))}`, + }; + } + return { + type: 'legacy', + legacyReference: [ + 'match', + opaqueString(input._id), + 'result.games', + String(game.gameNumber), + riotMatchId ?? + stableId( + competitionId, + 'legacy-game', + planned.series.id, + planned.ordinal, + ), + ].join(':'), + }; +} + +function addAdjudicationFacts( + input: LegacyMatchInput, + competitionId: string, + plannedGames: PlannedGame[], + teamIds: Map, + graph: SeriesDefinition[], + pending: PendingFact[], + reasons: CompetitionMigrationIssue[], +): void { + const gameSeriesIds = new Set(plannedGames.map((game) => game.series.id)); + const adjudicatedSeriesIds = new Set(); + + for (const bracketMatch of input.doubleElimination?.bracketMatches ?? []) { + const walkover = bracketMatch.walkover; + if (!walkover?.active) continue; + const series = graph.find( + (candidate) => candidate.code === bracketMatch.bracketMatchId, + ); + const winnerTeamId = teamIds.get(walkover.winnerTeamIndex); + if (!series || !winnerTeamId) { + reasons.push( + issue( + 'WALKOVER_MAPPING_NOT_FOUND', + `Active walkover ${bracketMatch.bracketMatchId} cannot be mapped.`, + { bracketMatchId: bracketMatch.bracketMatchId }, + ), + ); + continue; + } + if (gameSeriesIds.has(series.id)) { + reasons.push( + issue( + 'WALKOVER_CONFLICTS_WITH_GAMES', + `Series ${bracketMatch.bracketMatchId} has both active games and a walkover.`, + { seriesId: series.id }, + ), + ); + continue; + } + addAdjudication({ + competitionId, + series, + winnerTeamId, + decisionType: 'walkover', + reason: walkover.reason?.trim() || 'legacy-walkover', + occurredAt: normalizeDate(walkover.awardedAt, sourceFallbackDate(input)), + graph, + pending, + logicalSuffix: 'walkover', + }); + adjudicatedSeriesIds.add(series.id); + } + + for (const result of input.result?.seriesResults ?? []) { + if (!result.winnerTeamIndex) continue; + const resolution = resolveSeriesResult(graph, result, teamIds); + if ('issue' in resolution) { + reasons.push(resolution.issue); + continue; + } + const { series } = resolution; + if (gameSeriesIds.has(series.id) || adjudicatedSeriesIds.has(series.id)) + continue; + const winnerTeamId = teamIds.get(result.winnerTeamIndex); + if (!winnerTeamId) { + reasons.push( + issue( + 'WINNER_ONLY_RESULT_REFERENCES_UNKNOWN_TEAM', + 'A winner-only Series references an unknown team.', + { winnerTeamIndex: result.winnerTeamIndex, seriesId: series.id }, + ), + ); + continue; + } + addAdjudication({ + competitionId, + series, + winnerTeamId, + decisionType: 'administrative', + reason: 'legacy-winner-only-result', + occurredAt: seriesCompletionDate(input, series.code), + graph, + pending, + logicalSuffix: 'winner-only', + }); + adjudicatedSeriesIds.add(series.id); + } + + if ( + input.result?.winnerTeamIndex && + graph.length === 1 && + !gameSeriesIds.has(graph[0].id) && + !adjudicatedSeriesIds.has(graph[0].id) + ) { + const winnerTeamId = teamIds.get(input.result.winnerTeamIndex); + if (!winnerTeamId) { + reasons.push( + issue( + 'WINNER_ONLY_RESULT_REFERENCES_UNKNOWN_TEAM', + 'The Match winner references an unknown team.', + { winnerTeamIndex: input.result.winnerTeamIndex }, + ), + ); + } else { + addAdjudication({ + competitionId, + series: graph[0], + winnerTeamId, + decisionType: 'administrative', + reason: 'legacy-winner-only-result', + occurredAt: sourceFallbackDate(input), + graph, + pending, + logicalSuffix: 'match-winner-only', + }); + } + } +} + +function resolveSeriesResult( + graph: SeriesDefinition[], + result: LegacySeriesResultInput, + teamIds: Map, +): { series: SeriesDefinition } | { issue: CompetitionMigrationIssue } { + if (result.bracketMatchId) { + const series = graph.find( + (candidate) => candidate.code === result.bracketMatchId, + ); + return series + ? { series } + : { + issue: issue( + 'WINNER_ONLY_SERIES_MAPPING_NOT_FOUND', + `Winner-only bracket code ${result.bracketMatchId} has no Series.`, + ), + }; + } + const left = teamIds.get(result.teamAIndex); + const right = teamIds.get(result.teamBIndex); + if (!left || !right) { + return { + issue: issue( + 'WINNER_ONLY_RESULT_REFERENCES_UNKNOWN_TEAM', + 'A winner-only Series references an unknown team.', + ), + }; + } + const candidates = graph.filter((series) => + staticSeriesHasTeamSet(series, left, right), + ); + if (candidates.length !== 1) { + return { + issue: issue( + candidates.length > 1 + ? 'AMBIGUOUS_WINNER_ONLY_SERIES_MAPPING' + : 'WINNER_ONLY_SERIES_MAPPING_NOT_FOUND', + 'A winner-only Series cannot be mapped without guessing.', + { candidateSeriesIds: candidates.map((series) => series.id) }, + ), + }; + } + return { series: candidates[0] }; +} + +function addAdjudication(params: { + competitionId: string; + series: SeriesDefinition; + winnerTeamId: string; + decisionType: 'walkover' | 'administrative'; + reason: string; + occurredAt: string; + graph: SeriesDefinition[]; + pending: PendingFact[]; + logicalSuffix: string; +}): void { + params.pending.push({ + kind: 'series-adjudicated', + seriesOrder: params.graph.indexOf(params.series), + occurredAt: params.occurredAt, + logicalKey: `adjudication:${params.series.id}:${params.logicalSuffix}`, + build: (base) => ({ + ...base, + type: 'series-adjudicated', + seriesId: params.series.id, + decision: { + type: params.decisionType, + winnerTeamId: params.winnerTeamId, + }, + reason: params.reason, + }), + }); +} + +function materializeFacts( + competitionId: string, + migrationRunId: string, + recordedAt: string, + pending: PendingFact[], +): CompetitionMigrationFact[] { + const sorted = [...pending].sort( + (left, right) => + left.occurredAt.localeCompare(right.occurredAt) || + left.seriesOrder - right.seriesOrder || + left.logicalKey.localeCompare(right.logicalKey), + ); + return sorted.map((fact, index) => { + const revision = index + 1; + const id = stableId(competitionId, 'fact', fact.logicalKey); + const commandId = stableId( + competitionId, + 'migration-command', + fact.logicalKey, + ); + const base: MigrationFactBase = { + id, + competitionId, + revision, + ordinalWithinRevision: 1, + commandId, + idempotencyKey: `${migrationRunId}:${fact.logicalKey}`, + requestHash: `sha256:${stableHash(fact.logicalKey)}`, + schemaVersion: SCHEMA_VERSION, + actor: { type: 'migration', migrationRunId }, + occurredAt: fact.occurredAt, + recordedAt, + }; + return fact.build(base); + }); +} + +function buildAssignments( + input: LegacyMatchInput, + competitionId: string, + plannedGames: PlannedGame[], + facts: CompetitionMigrationFact[], + graph: SeriesDefinition[], + warnings: CompetitionMigrationIssue[], + reasons: CompetitionMigrationIssue[], +): CompetitionMigrationAssignment[] { + const result: CompetitionMigrationAssignment[] = []; + for (const code of input.tournamentCodes ?? []) { + if ( + code.state !== 'reserved' && + code.state !== 'used' && + code.state !== 'released' && + code.state !== 'voided' + ) { + continue; + } + const tournamentCodeId = opaqueString(code._id); + const gameFact = facts.find( + (fact): fact is MigrationGameAcceptedFact => + fact.type === 'game-accepted' && + code.riotMatchId !== undefined && + ((fact.evidence.type === 'riot' && + fact.evidence.riotMatchId === code.riotMatchId) || + (fact.evidence.type === 'legacy' && + fact.evidence.legacyReference.endsWith(`:${code.riotMatchId}`))), + ); + let series = gameFact + ? graph.find((candidate) => candidate.id === gameFact.seriesId) + : graph.find((candidate) => candidate.code === code.bracketMatchId); + if (!series && code.gameNumber !== undefined) { + const game = plannedGames.find( + (candidate) => candidate.legacy.gameNumber === code.gameNumber, + ); + series = game?.series; + } + if (!series) { + reasons.push( + issue( + 'TOURNAMENT_CODE_ASSIGNMENT_MAPPING_NOT_FOUND', + 'A non-available TournamentCode cannot be mapped to a stable GameSlot.', + { + tournamentCodeId, + bracketMatchId: code.bracketMatchId, + gameNumber: code.gameNumber, + }, + ), + ); + continue; + } + + let slot = gameFact + ? series.gameSlots.find( + (candidate) => candidate.id === gameFact.gameSlotId, + ) + : undefined; + if (!slot && code.gameNumber !== undefined && code.bracketMatchId) { + const legacyBracket = input.doubleElimination?.bracketMatches?.find( + (candidate) => candidate.bracketMatchId === code.bracketMatchId, + ); + const ordinal = legacyBracket?.gameNumber + ? code.gameNumber - legacyBracket.gameNumber + 1 + : undefined; + slot = series.gameSlots.find( + (candidate) => candidate.ordinal === ordinal, + ); + } + slot ??= series.gameSlots[0]; + if (!slot) { + reasons.push( + issue( + 'TOURNAMENT_CODE_ASSIGNMENT_MAPPING_NOT_FOUND', + 'A TournamentCode Series has no stable GameSlot.', + { tournamentCodeId, seriesId: series.id }, + ), + ); + continue; + } + if (code.state === 'used' && !gameFact) { + warnings.push( + issue( + 'USED_CODE_WITHOUT_ACCEPTED_GAME', + 'A used TournamentCode has no accepted legacy game evidence.', + { tournamentCodeId, gameSlotId: slot.id }, + ), + ); + } + const reservedAt = normalizeDate( + code.reservedAt, + normalizeDate(code.usedAt, sourceFallbackDate(input)), + ); + result.push({ + id: stableId( + competitionId, + 'tournament-code-assignment', + tournamentCodeId, + ), + competitionId, + seriesId: series.id, + gameSlotId: slot.id, + tournamentCodeId, + state: code.state, + reservedAt, + ...(code.usedAt + ? { usedAt: normalizeDate(code.usedAt, reservedAt) } + : {}), + ...(code.releasedAt + ? { releasedAt: normalizeDate(code.releasedAt, reservedAt) } + : {}), + ...(code.riotMatchId ? { riotMatchId: code.riotMatchId } : {}), + commandId: stableId( + competitionId, + 'migration-code-command', + tournamentCodeId, + ), + }); + } + + const activeSlots = new Set(); + const activeCodes = new Set(); + for (const assignment of result) { + if (assignment.state !== 'reserved' && assignment.state !== 'used') + continue; + if ( + activeSlots.has(assignment.gameSlotId) || + activeCodes.has(assignment.tournamentCodeId) + ) { + reasons.push( + issue( + 'AMBIGUOUS_TOURNAMENT_CODE_ASSIGNMENT', + 'Active TournamentCode assignments collide on identity or GameSlot.', + { + tournamentCodeId: assignment.tournamentCodeId, + gameSlotId: assignment.gameSlotId, + }, + ), + ); + } + activeSlots.add(assignment.gameSlotId); + activeCodes.add(assignment.tournamentCodeId); + } + return result.sort((left, right) => left.id.localeCompare(right.id)); +} + +function seriesCompletionDate(input: LegacyMatchInput, code?: string): string { + const completedAt = input.doubleElimination?.bracketMatches?.find( + (bracketMatch) => bracketMatch.bracketMatchId === code, + )?.completedAt; + return normalizeDate(completedAt, sourceFallbackDate(input)); +} + +function gameOccurrence( + game: LegacyGameInput, + input: LegacyMatchInput, +): string { + if (typeof game.gameCreation === 'number') { + const milliseconds = + game.gameCreation < 10_000_000_000 + ? game.gameCreation * 1000 + : game.gameCreation; + return normalizeDate(milliseconds, sourceFallbackDate(input)); + } + return normalizeDate(game.gameCreation, sourceFallbackDate(input)); +} + +function compareLegacyGames( + left: Omit, + right: Omit, +) { + return ( + gameOccurrence(left.legacy, { + createdAt: EPOCH, + } as LegacyMatchInput).localeCompare( + gameOccurrence(right.legacy, { createdAt: EPOCH } as LegacyMatchInput), + ) || + left.legacy.gameNumber - right.legacy.gameNumber || + (left.legacy.riotMatchId ?? '').localeCompare( + right.legacy.riotMatchId ?? '', + ) + ); +} + +function sourceFallbackDate(input: LegacyMatchInput): string { + return normalizeDate(input.updatedAt, normalizeDate(input.createdAt, EPOCH)); +} + +function normalizeDate(value: unknown, fallback: string): string { + if (value === undefined || value === null || value === '') return fallback; + const date = + value instanceof Date ? value : new Date(value as string | number); + return Number.isNaN(date.getTime()) ? fallback : date.toISOString(); +} + +function stableId(...parts: Array): string { + return createHash('sha256') + .update(JSON.stringify(parts)) + .digest('hex') + .slice(0, 24); +} + +function stableHash(value: string): string { + return createHash('sha256').update(value).digest('hex'); +} + +function canonicalize(value: unknown): string { + if (Array.isArray(value)) { + return `[${value.map(canonicalize).join(',')}]`; + } + if (value instanceof Date) return JSON.stringify(value.toISOString()); + if (value && typeof value === 'object') { + const record = value as Record; + return `{${Object.keys(record) + .sort() + .map((key) => `${JSON.stringify(key)}:${canonicalize(record[key])}`) + .join(',')}}`; + } + return JSON.stringify(value); +} + +function opaqueString(value: unknown): string { + if (typeof value === 'string') return value.trim(); + if (value === undefined || value === null) return ''; + const rendered = String(value); + return rendered === '[object Object]' ? '' : rendered; +} + +function positiveInteger(value: unknown): number | undefined { + return typeof value === 'number' && Number.isInteger(value) && value > 0 + ? value + : undefined; +} + +function issue( + code: string, + message: string, + details?: Record, +): CompetitionMigrationIssue { + return { + code, + message, + ...(details && Object.keys(details).length > 0 ? { details } : {}), + }; +} + +function quarantined( + matchId: string, + reasons: CompetitionMigrationIssue[], + warnings: CompetitionMigrationIssue[], +): QuarantinedCompetitionMigrationPlan { + return { + status: 'quarantined', + matchId, + reasons: sortedIssues(reasons), + warnings: sortedIssues(warnings), + }; +} + +function sortedIssues( + issues: CompetitionMigrationIssue[], +): CompetitionMigrationIssue[] { + return [...issues].sort( + (left, right) => + left.code.localeCompare(right.code) || + canonicalize(left.details).localeCompare(canonicalize(right.details)), + ); +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +function errorCodeDetails(error: unknown): Record | undefined { + if (!error || typeof error !== 'object' || !('code' in error)) + return undefined; + return { projectorCode: String((error as { code: unknown }).code) }; +}