import { addDays, addMonths, addYears, startOfMonth, startOfWeek, startOfYear, } from "date-fns"; import { fromZonedTime, toZonedTime } from "date-fns-tz"; import type { CalendarViewValue, SessionDatePresetValue } from "@/lib/constants"; import { APP_TIME_ZONE } from "@/lib/constants"; import { AppError } from "@/server/errors"; function normalizeCairoDate(input?: Date | string) { return toZonedTime(input ? new Date(input) : new Date(), APP_TIME_ZONE); } function toUtc(date: Date) { return fromZonedTime(date, APP_TIME_ZONE); } export function parseCairoDateTimeInput(value: string) { const trimmed = value.trim(); if (!trimmed) { throw new AppError("حدد التاريخ والوقت.", 400); } return fromZonedTime(trimmed, APP_TIME_ZONE); } export function getSessionRangeForPreset( preset: SessionDatePresetValue, now = new Date(), ) { if (preset === "all") { return undefined; } const zonedNow = normalizeCairoDate(now); const start = new Date(zonedNow); start.setHours(0, 0, 0, 0); if (preset === "today") { return { gte: toUtc(start), lt: toUtc(addDays(start, 1)), }; } if (preset === "tomorrow") { const tomorrow = addDays(start, 1); return { gte: toUtc(tomorrow), lt: toUtc(addDays(tomorrow, 1)), }; } if (preset === "thisWeek") { const weekStart = startOfWeek(start, { weekStartsOn: 6 }); return { gte: toUtc(weekStart), lt: toUtc(addDays(weekStart, 7)), }; } if (preset === "thisMonth") { const monthStart = startOfMonth(start); return { gte: toUtc(monthStart), lt: toUtc(addMonths(monthStart, 1)), }; } const yearStart = startOfYear(start); return { gte: toUtc(yearStart), lt: toUtc(addYears(yearStart, 1)), }; } export function getCalendarRange( view: CalendarViewValue, anchor?: string, ) { const zonedAnchor = normalizeCairoDate(anchor); const start = view === "week" ? startOfWeek(zonedAnchor, { weekStartsOn: 6 }) : startOfMonth(zonedAnchor); const end = view === "week" ? addDays(start, 7) : addMonths(start, 1); return { start, end, gte: toUtc(start), lt: toUtc(end), anchor: toUtc(start), }; }