import type { Payload } from "payload"; import { derivePeriodForInstant, periodStartForIndex } from "./derive"; import { resolveMinigameRules, type ResolvedMinigameRules } from "./rules"; /** * Single write path for the `minigame-entries` append-only ledger. * * Called by the five Core minigame submit actions AFTER their profile update, * so a completed, scored run is always recorded (and never allowed to break * the game submission: every failure is swallowed and logged). * * The period is resolved lazily: the first entry in an anchored period creates * that period (idempotently; a unique `startDate` guards concurrent writers), * so the ledger has a period reference even before the period tick has ever * run. Phase 2's close pipeline then closes it at its end boundary. */ export interface RecordMinigameEntryInput { payload: Payload; userId: number; /** Registry key (minigames.key), e.g. "flappy". */ game: string; score: number; durationMs: number; accuracy?: number | null; mode?: string | null; meta?: Record | null; /** Injectable clock, for tests. */ now?: Date; } const findPeriodIdByStart = async (payload: Payload, startIso: string): Promise => { const res = await payload.find({ collection: "minigame-periods", where: { startDate: { equals: startIso } }, limit: 1, depth: 0, overrideAccess: true, }); return res.docs[0]?.id ?? null; }; /** Find or lazily create the anchored period containing `instant`. */ export const ensurePeriodForInstant = async ( payload: Payload, rules: ResolvedMinigameRules, instant: Date, ): Promise => { if (!rules.enabled || !rules.anchorDate) return null; const derived = derivePeriodForInstant(rules.anchorDate, rules.periodLengthDays, instant); if (!derived) return null; const startIso = derived.startDate.toISOString(); const existingId = await findPeriodIdByStart(payload, startIso); if (existingId != null) return existingId; let previousPeriodId: number | null = null; if (derived.index > 0) { const prevStart = periodStartForIndex( rules.anchorDate, rules.periodLengthDays, derived.index - 1, ).toISOString(); previousPeriodId = await findPeriodIdByStart(payload, prevStart); } try { const created = await payload.create({ collection: "minigame-periods", data: { startDate: startIso, endDate: derived.endDate.toISOString(), label: derived.label, status: "open", previousPeriod: previousPeriodId, }, overrideAccess: true, depth: 0, }); return created.id; } catch { // Lost a race to another writer; the unique startDate means ours is there. return findPeriodIdByStart(payload, startIso); } }; export async function recordMinigameEntry(input: RecordMinigameEntryInput): Promise { const { payload } = input; try { const instant = input.now ?? new Date(); const rules = await resolveMinigameRules(payload); const periodId = await ensurePeriodForInstant(payload, rules, instant); const durationMs = Number.isFinite(input.durationMs) && input.durationMs >= 0 ? Math.round(input.durationMs) : 0; await payload.create({ collection: "minigame-entries", data: { user: input.userId, game: input.game, mode: input.mode ?? null, score: input.score, accuracy: input.accuracy ?? null, durationMs, occurredAt: instant.toISOString(), period: periodId, meta: input.meta ?? null, }, overrideAccess: true, depth: 0, }); } catch (error) { // Never fail the player's submission because the ledger hiccuped. const message = error instanceof Error ? error.message : String(error); try { payload.logger.error(`[Minigames] Failed to record ${input.game} entry: ${message}`); } catch { // ignore logging failures } } }