import type { CommunityId, CompetitionDetailResponse, CompetitionFormat, CompetitionId, CompetitionPhase, CompetitionProjection, MatchId, PlayerPosition, TeamId, UserId, } from '@lolympus/contracts'; type IdLike = string | { toString(): string }; interface CompetitionMemberSource { userId: IdLike; displayName: string; gameName?: string; tagLine?: string; profileIconId?: number; assignedPosition?: string; cost?: number; [key: string]: unknown; } interface CompetitionTeamSource { teamId: IdLike; displayOrder: number; name: string; captainUserId?: IdLike; members: CompetitionMemberSource[]; [key: string]: unknown; } export interface CompetitionDetailSource { _id: IdLike; matchId: IdLike; communityId: IdLike; schemaVersion: number; revision: number; phase: CompetitionPhase; teams: CompetitionTeamSource[]; format: Record; projection: Record; createdAt: Date | string; updatedAt: Date | string; [key: string]: unknown; } /** Build the public wire DTO without ever spreading a persistence document. */ export function presentCompetitionDetail( source: CompetitionDetailSource, ): CompetitionDetailResponse { return { id: asId(source._id), matchId: asId(source.matchId), communityId: asId(source.communityId), schemaVersion: source.schemaVersion, revision: source.revision, phase: source.phase, teams: source.teams.map((team) => ({ teamId: asId(team.teamId), displayOrder: team.displayOrder, name: team.name, ...(team.captainUserId ? { captainUserId: asId(team.captainUserId) } : {}), members: team.members.map((member) => ({ userId: asId(member.userId), displayName: member.displayName, ...(member.gameName ? { gameName: member.gameName } : {}), ...(member.tagLine ? { tagLine: member.tagLine } : {}), ...(member.profileIconId !== undefined ? { profileIconId: member.profileIconId } : {}), ...(member.assignedPosition ? { assignedPosition: member.assignedPosition as PlayerPosition } : {}), ...(member.cost !== undefined ? { cost: member.cost } : {}), })), })), format: toWireValue(source.format) as CompetitionFormat, projection: toWireValue(source.projection) as CompetitionProjection, createdAt: asIsoDateTime(source.createdAt), updatedAt: asIsoDateTime(source.updatedAt), }; } function asId(value: IdLike): T { return value.toString() as T; } function asIsoDateTime(value: Date | string): string { return value instanceof Date ? value.toISOString() : value; } function toWireValue(value: unknown): unknown { if (value instanceof Date) return value.toISOString(); if (Array.isArray(value)) return value.map(toWireValue); if (isPlainRecord(value)) { return Object.fromEntries( Object.entries(value).map(([key, entry]) => [key, toWireValue(entry)]), ); } return value; } function isPlainRecord(value: unknown): value is Record { return ( typeof value === 'object' && value !== null && Object.getPrototypeOf(value) === Object.prototype ); }