## Booking timezones and time types: current state, issues, and alignment plan

### Scope and goal
This document explains how booking availability is computed across the admin layer and calculator, how time types and timezones are used today, where mismatches occur, and what to align to make results consistent in every environment and across DST.

Applies to:
- `Api/src/admin/booking/booking.admin.ts`
- `Api/src/admin/booking/booking.calculator.ts`
- `Api/src/admin/booking/booking.types.ts`

### High-level flow (availability)
1) `BookingAdmin.getAvailableBookingSlots`
   - Accepts timeframe as `Date` or `admin.firestore.Timestamp` and normalizes to admin Timestamp.
   - Loads `clinic`, `practitioner`, `procedure`.
   - Fetches calendar events for clinic and practitioner within the timeframe using admin Timestamps.
   - Converts all timestamps (timeframe and events) to client `firebase/firestore` `Timestamp` for the calculator via `TimestampUtils.adminToClient`.
   - Passes clinic timezone `tz = clinic.location.tz` to the calculator.
   - Calls `BookingAvailabilityCalculator.calculateSlots`.
   - Converts resulting client `Timestamp`s back to admin Timestamp in the response.

2) `BookingAvailabilityCalculator.calculateSlots`
   - Uses client `Timestamp` + Luxon `DateTime`.
   - Steps: apply clinic working hours → subtract clinic blocking events → apply practitioner working hours for the target clinic → subtract practitioner busy times → generate slots on a fixed interval grid.

3) Types (`BookingAvailabilityRequest`)
   - Requires that all time values be client `Timestamp` (from `firebase/firestore`).
   - Admin layer converts before calling the calculator and converts back afterwards.

### Time representations in play
- Admin/server: `admin.firestore.Timestamp` (backend)
- Client/runtime in calculator: `firebase/firestore` `Timestamp`
- Luxon `DateTime` for tz-aware computations
- String wall-clock specs in working hours, e.g. "HH:mm" for open/close/breaks
- JavaScript `Date` only used transiently at boundaries

### Where timezone handling is correct
- Building per-day working-hour intervals (clinic and practitioner) uses:
  - `DateTime.fromMillis(value, { zone: tz })` (avoids local-time reinterpretation)
  - Explicit `tz` carried from `clinic.location.tz`

### Where timezone context is dropped (root cause of shifts)
- Slot generation rounds and iterates using system-local timezone instead of clinic `tz`.
- Slot containment checks compare times constructed without explicit `tz`.
- Effects:
  - Servers not in the clinic’s zone (e.g., UTC) will produce slots offset or misaligned to the expected clinic grid.
  - DST boundaries can produce off-by-60-min effects and incorrect inclusion/exclusion of slots.

Problematic patterns to replace:
```ts
// Uses system-local timezone implicitly
let slotStart = DateTime.fromJSDate(intervalStart);

// Also builds DateTimes without { zone: tz }
const intervalStart = DateTime.fromMillis(interval.start.toMillis());
const intervalEnd = DateTime.fromMillis(interval.end.toMillis());
```

Target pattern:
```ts
// Always specify the clinic timezone
let slotStart = DateTime.fromMillis(intervalStartMillis, { zone: tz });
const intervalStart = DateTime.fromMillis(interval.start.toMillis(), { zone: tz });
const intervalEnd = DateTime.fromMillis(interval.end.toMillis(), { zone: tz });
```

### Event retrieval misses overlapping events
- Current queries fetch events with `eventTime.start` within `[timeframe.start, timeframe.end]` only.
- Events that start before the window but overlap into it (or extend beyond it) are omitted, so busy time subtraction can miss conflicts.

Correct overlapping logic should include events where:
- `eventTime.start < timeframe.end` AND `eventTime.end > timeframe.start`

Firestore considerations:
- Firestore cannot do range filters on two different fields in a single query without workarounds. Practical options:
  - Run two queries and union results, or
  - Add a single-field index (e.g., duplicated fields like `startAt` and `endAt`) and leverage composite queries appropriately, or
  - Query the broader of the two constraints and post-filter in memory. De-duplicate by `id`.

### Appointment creation normalization
- `orchestrateAppointmentCreation` writes calendar events with `eventTime` taken directly from input admin Timestamps.
- If the client produced those Timestamps by converting wall-clock times in a different timezone than the clinic, users will observe unexpected local renderings relative to clinic working hours.

Alignment expectation:
- UI should interpret user-picked wall-clock times in the clinic’s `tz`, convert once to UTC epoch, and send as Timestamp.
- Backend stores the UTC epoch as-is; all display/logic that needs wall-clock context must apply the clinic `tz` explicitly.

### Alignment decisions (non-code policy)
1) Single invariant for the calculator
   - Inputs are client `Timestamp`s (UTC epoch) plus explicit `tz`.
   - Every Luxon `DateTime` must be created with `{ zone: tz }`.
   - Prefer `DateTime.fromMillis(...)` over `fromJSDate(...)`.

2) Slot generation/containment
   - `generateAvailableSlots` uses `tz` when rounding to interval grid and when iterating.
   - `isSlotFullyAvailable` constructs interval boundaries with `{ zone: tz }`.

3) Event retrieval strategy
   - For timeframe `[S, E]`, include events where `start < E` and `end > S`.
   - Implement via union of queries or data model support; post-filter and de-dup in memory if needed.

4) Conversion boundaries
   - Admin layer converts admin → client Timestamps only at the calculator boundary and client → admin at the response boundary.
   - Do not mix admin/client Timestamp types in a single object passed to the calculator.

5) UI and API contract
   - UI times are wall-clock in clinic `tz`, converted once to UTC Timestamp before sending.
   - Backend accepts/returns admin Timestamps on API, but calculator-only paths use client Timestamps internally.

### Testing matrix (must pass)
- Timezone variance:
  - Clinics in multiple IANA zones; server in UTC and in a non-UTC zone.
- DST boundaries:
  - Days that enter/exit DST in clinic `tz`.
- Timeframe edges:
  - Windows that straddle midnight in clinic `tz`.
  - Very short windows (e.g., ≤ duration) and long windows (multi-day).
- Event overlap cases:
  - Events starting before S and ending between S..E.
  - Events starting between S..E and ending after E.
  - Long events fully covering S..E.
- Grid checks:
  - Interval sizes that don’t divide 60 (e.g., 20 min), and variable procedure durations.

### Actionable checklist
- ✅ Make all DateTime constructions in slot generation and containment checks use `{ zone: tz }`.
- ✅ Replace `fromJSDate` with `fromMillis` in calculator paths.
- ✅ Update event fetching to include overlaps with the timeframe; union queries or adjust model.
- ⏳ Re-assert the type contract: calculator receives only client `Timestamp` + `tz`.
- ⏳ Document UI responsibility to convert wall-clock (clinic `tz`) → UTC Timestamp exactly once.

### PHASE 1 COMPLETED: Backend Calculator Fixes ✅

**Date Completed:** October 1, 2025

**Changes Made:**

1. **booking.calculator.ts - generateAvailableSlots()**
   - Added `tz: string` parameter
   - Changed `DateTime.fromJSDate(intervalStart)` → `DateTime.fromMillis(intervalStart.getTime(), { zone: tz })`
   - Now explicitly creates DateTime in clinic timezone for all slot calculations
   
2. **booking.calculator.ts - isSlotFullyAvailable()**
   - Added `tz: string` parameter
   - Changed `DateTime.fromMillis(interval.start.toMillis())` → `DateTime.fromMillis(interval.start.toMillis(), { zone: tz })`
   - Interval boundary checks now use clinic timezone context

3. **booking.calculator.ts - calculateSlots()**
   - Updated call to `generateAvailableSlots()` to pass `tz` parameter
   - Updated call to `isSlotFullyAvailable()` to pass `tz` parameter

4. **booking.admin.ts - getClinicCalendarEvents()**
   - Fixed event overlap logic with bounded query
   - Added lower bound: `queryStart = start - 24 hours` to prevent querying all historical events
   - Query: `eventTime.start >= queryStart AND eventTime.start < end`
   - Added post-filter: `eventTime.end > start` to catch all overlapping events
   - Prevents missing events that start before window but overlap into it
   - Performance optimized: only queries ~24-48 hours of events instead of entire history

5. **booking.admin.ts - getPractitionerCalendarEvents()**
   - Applied same overlap fix with 24-hour lookback window
   - Ensures busy time subtraction includes all conflicting events
   - Efficient: assumes no appointments longer than 24 hours

**Impact:**
- Slot generation now correctly happens in clinic timezone
- Slots are properly converted to UTC for storage/transmission
- Event blocking now catches all overlapping events, not just those starting within window
- Fixes timezone display issues for users in different timezones

**Next Steps:**
- Phase 2: Mobile app fixes (use original UTC timestamp from slots)
- Phase 3: ClinicApp fixes (same as Mobile)
- Phase 4: Testing across multiple timezones and DST boundaries

### Known risks
- DST transitions can produce days with 23/25 hours; rounding/iteration must not assume 24h.
- Post-filtering events after union queries can be memory-intensive for very large windows; constrain timeframe appropriately.

### Quick glossary
- Admin Timestamp: `admin.firestore.Timestamp` (backend SDK)
- Client Timestamp: `firebase/firestore` `Timestamp` (web SDK)
- `tz`: Clinic’s IANA timezone string, e.g., `Europe/Belgrade`
- Luxon `DateTime`: tz-aware date-time object used for calendar math


