import type { WeekDay } from '@gruperly/shared'; import { todayOccurrence } from '@/modules/home/lib/scheduler'; import type { ClassesDb } from './helpers'; export type TodaySessionCandidate = { groupId: string; startsAt: Date; }; type ScheduledGroup = { id: string; days: WeekDay[] | null; time: string | null; }; // Computes which groups have a class today (from days/time and the teacher's time zone). export function buildTodayCandidates( groups: ScheduledGroup[], now: Date, timeZone: string, ): TodaySessionCandidate[] { const candidates: TodaySessionCandidate[] = []; for (const group of groups) { if (!group.days || group.days.length === 0 || !group.time) { continue; } const startsAt = todayOccurrence({ days: group.days, time: group.time, now, timeZone, }); if (startsAt) { candidates.push({ groupId: group.id, startsAt }); } } return candidates; } // Materializes (idempotent upsert) today's ClassSession rows and returns their ids. export async function ensureTodaySessions( db: Pick, candidates: TodaySessionCandidate[], ): Promise { const sessionIds: string[] = []; for (const candidate of candidates) { const session = await db.classSession.upsert({ where: { groupId_startsAt: { groupId: candidate.groupId, startsAt: candidate.startsAt, }, }, create: { groupId: candidate.groupId, startsAt: candidate.startsAt, }, update: {}, select: { id: true }, }); sessionIds.push(session.id); } return sessionIds; }