# Appointment Aggregation Service (`appointment.aggregation.service.ts`)

This service is responsible for handling side effects and data aggregation tasks related to the lifecycle of appointments within the system. It is primarily designed to be invoked by Firestore triggers (`onCreate`, `onUpdate`, `onDelete`) for the `appointments` collection.

## Core Responsibilities

- Managing denormalized data links (e.g., patient-clinic, patient-practitioner).
- Creating and updating `PatientRequirementInstance` documents based on appointment status and associated procedure requirements.
- Orchestrating notifications (email and push) to patients, practitioners, and clinic admins at various stages of the appointment lifecycle.
- Interfacing with other admin services like `AppointmentMailingService`, `NotificationsAdmin`, `CalendarAdminService`, and `ResourceCalendarAdminService`.
- Managing resource calendar events for appointments that have booked clinic resources (see [Resource System](../../../../../docs/RESOURCE_SYSTEM.md)).

## Implemented Functionality

### Constructor

- Initializes with a Firestore instance and a Mailgun client.
- Sets up instances of dependent services: `AppointmentMailingService`, `NotificationsAdmin`, `CalendarAdminService`, `ResourceCalendarAdminService`, and `PatientRequirementsAdminService`.
  - **`ResourceCalendarAdminService`**: Manages resource calendar events (status updates, time updates, deletion) for appointments that have `resourceBookings`. See [Resource System README](../../../../../docs/RESOURCE_SYSTEM.md).
  - **Note**: `PatientRequirementsAdminService` is initialized but its methods are not (and should not be) directly called by this aggregation service for creating/managing requirement instances. That logic is correctly handled by local private methods in this service.

### `handleAppointmentCreate(appointment: Appointment)`

- **Patient-Clinic-Practitioner Links**: Calls `managePatientClinicPractitionerLinks` to add links.
- **Data Fetching**: Fetches `PatientProfile`, `PatientSensitiveInfo`, `PractitionerProfile`, and `Clinic` data.
- **Status: `CONFIRMED`**
  - Creates pre-appointment requirement instances via `createPreAppointmentRequirementInstances()`.
  - Sends confirmation email to patient via `appointmentMailingService.sendAppointmentConfirmedEmail()`.
  - Sends confirmation email to practitioner via `appointmentMailingService.sendAppointmentConfirmedEmail()`.
  - Initiates confirmed push notification to patient via `notificationsAdmin.sendAppointmentConfirmedPush()`.
- **Status: `PENDING`**
  - Sends appointment requested email to clinic admin via `appointmentMailingService.sendAppointmentRequestedEmailToClinic()`.

### `handleAppointmentUpdate(before: Appointment, after: Appointment)`

- **Data Fetching**: Fetches `PatientProfile`, `PatientSensitiveInfo`, `PractitionerProfile`, and `Clinic` data for the `after` state.
- **Status Change: `PENDING -> CONFIRMED`**
  - Creates pre-appointment requirement instances via `createPreAppointmentRequirementInstances(after)`.
  - Sends confirmation email to patient.
  - Sends confirmation email to practitioner.
  - Initiates confirmed push notification to patient.
- **Status Change: `Any -> CANCELLED_*` (includes `NO_SHOW`)**
  - Updates related patient requirement instances to `CANCELLED_APPOINTMENT` via `updateRelatedPatientRequirementInstances()`.
  - Removes patient-clinic-practitioner links via `managePatientClinicPractitionerLinks()`.
  - Sends cancellation email to patient.
  - Sends cancellation email to practitioner.
- **Status Change: `Any -> COMPLETED`**
  - Creates post-appointment requirement instances via `createPostAppointmentRequirementInstances(after)`.
  - Sends review request email to patient.
- **Status Change: `Any -> RESCHEDULED_BY_CLINIC`**
  - Updates related (old) patient requirement instances to `SUPERSEDED_RESCHEDULE`.
  - Sends reschedule proposal email to patient.

### `handleAppointmentDelete(deletedAppointment: Appointment)`

- Updates related patient requirement instances to `CANCELLED_APPOINTMENT`.
- Removes patient-clinic-practitioner links.

### Helper Methods

- **`createPreAppointmentRequirementInstances(appointment: Appointment)`**:
  - Creates `PatientRequirementInstance` documents for pre-appointment requirements based on `appointment.preProcedureRequirements`.
  - Calculates due times for instructions based on `appointment.appointmentStartTime`.
  - **Same-day notification handling**: For `notifyAt: 0` with `unit: "days"`, notifications are sent at 8 AM instead of the appointment time. If the appointment is before 8 AM, the notification is sent 2 hours before the appointment.
  - Sets `actionableWindow` with a placeholder value (TODO noted).
  - Batch writes instances to Firestore.
- **`createPostAppointmentRequirementInstances(appointment: Appointment)`**:
  - Creates `PatientRequirementInstance` documents for post-appointment requirements based on `appointment.postProcedureRequirements`.
  - Calculates due times for instructions based on `appointment.appointmentEndTime`.
  - Sets `actionableWindow` with a placeholder value (TODO noted).
  - Batch writes instances to Firestore.
- **`updateRelatedPatientRequirementInstances(appointment: Appointment, newOverallStatus: PatientRequirementOverallStatus)`**:
  - Queries for all `PatientRequirementInstance` documents linked to the appointment.
  - Batch updates their `overallStatus` and `updatedAt` fields.
- **`managePatientClinicPractitionerLinks(appointment: Appointment, action: "create" | "cancel")`**:
  - Adds/removes the patient's ID from `patientIds` arrays on the respective clinic and practitioner documents using `FieldValue.arrayUnion` or `FieldValue.arrayRemove`.
- **Data Fetching Helpers (`fetchPatientProfile`, `fetchPatientSensitiveInfo`, `fetchPractitionerProfile`, `fetchClinicInfo`)**:
  - Basic methods to retrieve documents from Firestore by ID.

## Resource Calendar Event Handling

When an appointment has `resourceBookings` (i.e., the procedure required clinic resources), the aggregation service also manages resource calendar events via `ResourceCalendarAdminService`:

| Appointment Transition | Resource Calendar Action |
|---|---|
| `PENDING → CONFIRMED` | `resourceCalendarAdmin.updateResourceBookingEventsStatus(after, CONFIRMED)` |
| `RESCHEDULED_BY_CLINIC → CONFIRMED` | `resourceCalendarAdmin.updateResourceBookingEventsStatus(after, CONFIRMED)` |
| `Any → CANCELLED / NO_SHOW` | `resourceCalendarAdmin.updateResourceBookingEventsStatus(after, calendarStatus)` |
| `Any → COMPLETED` | `resourceCalendarAdmin.updateResourceBookingEventsStatus(after, COMPLETED)` |
| `Any → RESCHEDULED_BY_CLINIC` | `resourceCalendarAdmin.updateResourceBookingEventsTime(after, newTime)` + `updateResourceBookingEventsStatus(after, PENDING)` |
| Time change (CONFIRMED, no status change) | `resourceCalendarAdmin.updateResourceBookingEventsTime(after, newTime)` |
| Appointment deleted | `resourceCalendarAdmin.deleteResourceBookingEvents(deletedAppointment)` |

All resource operations are guarded by checking `appointment.resourceBookings` existence, so backward-compatible appointments (without resources) are unaffected.

For full details on the resource system, see [Resource System README](../../../../../docs/RESOURCE_SYSTEM.md).

---

## Pending `TODO` Items & Areas for Future Work

### General / Cross-Cutting

- **Type Imports for Email Data Objects**:
  - Throughout `handleAppointmentCreate` and `handleAppointmentUpdate`, calls to the `appointmentMailingService` use `as any` for the data payload (e.g., `emailData as any`).
  - `TODO`: Properly import `PatientProfileInfo`, `PractitionerProfileInfo`, `ClinicInfo` from a shared location (e.g., `Api/src/types/profile.ts` or `Api/src/types/index.ts`) and ensure these types are correctly used, removing the `as any` casts. This may require exporting these types if they are not already.
- **`actionableWindow` in Requirement Instances**:
  - In `createPreAppointmentRequirementInstances` and `createPostAppointmentRequirementInstances`, the `actionableWindow` for instructions is currently a placeholder (e.g., based on importance or a fixed value like 24 hours).
  - `TODO`: Determine the correct logic or source for `actionableWindow` based on business requirements or template definitions.
- **Error Handling**: Enhance error handling in various methods to potentially update appointment status to an error state or implement more sophisticated retry mechanisms if critical operations fail.

### `handleAppointmentCreate(appointment: Appointment)`

- **Push Notifications**:
  - `TODO`: Implement sending appointment confirmed push to practitioner (if they have expo tokens).
  - `TODO`: Implement sending pending appointment push notification to clinic admin (if applicable).

### `handleAppointmentUpdate(before: Appointment, after: Appointment)`

- **Push Notifications**:
  - For `PENDING -> CONFIRMED`: `TODO`: Send appointment confirmed push to practitioner.
  - For `Any -> CANCELLED_*`: `TODO`: Send cancellation push notifications to patient and practitioner.
  - For `Any -> COMPLETED`: `TODO`: Send review request push notification to patient.
  - For `Any -> RESCHEDULED_BY_CLINIC`: `TODO`: Send reschedule proposal push notifications to patient (and practitioner if applicable).
- **Calendar Event Updates**:
  - For `Any -> CANCELLED_*`: `TODO`: Update/cancel calendar event via `calendarAdminService.updateAppointmentCalendarEventStatus(after, CalendarEventStatus.CANCELED)` (or similar method).
  - For `Any -> RESCHEDULED_BY_CLINIC`: `TODO`: Update calendar event to reflect proposed new time via `calendarAdminService`.
- **Reschedule Logic for Requirements (`RESCHEDULED_BY_CLINIC`)**:
  - `TODO`: Handle RESCHEDULE logic for `PatientRequirementInstance` creation/cancellation more carefully based on the specific confirmation flow of a reschedule. For instance, when are new pre-requirements created if it's just a proposal?
- **Reschedule Notification to Practitioner (`RESCHEDULED_BY_CLINIC`)**:
  - `TODO`: Implement sending reschedule proposal email/notification to the practitioner.
- **Independent Time Change**:
  - `TODO`: Fully implement logic for when `appointmentStartTime` or `appointmentEndTime` changes without an accompanying status change. This might involve updating requirements and calendar events.
  - `Logger.warn` currently flags this scenario.
- **Payment Status Change**:
  - `TODO`: Implement logic for `before.paymentStatus !== after.paymentStatus`. This could involve sending payment confirmation notifications (email/push).
- **Review Added**:
  - `TODO`: Implement logic for when `!before.reviewInfo && after.reviewInfo`. This could involve notifying the clinic admin or practitioner.

### `handleAppointmentDelete(deletedAppointment: Appointment)`

- **Notifications**: `TODO`: Send cancellation/deletion notifications if appropriate (though data is gone, so context might be limited).
- **Calendar Events**: Placeholder comment `// await this.calendarAdminService.deleteAppointmentCalendarEvents(deletedAppointment);` exists.
  - `TODO`: Implement actual call to delete associated calendar events.

### `managePatientClinicPractitionerLinks(...)`

- **Robust Removal Logic**:
  - `TODO`: For the 'cancel' action, implement more robust removal logic. Currently, it removes the patient ID regardless. It should ideally only remove the link if this was the last active/confirmed appointment connecting the patient to the practitioner/clinic.

This README should serve as a good guide to the current state and future development of the `AppointmentAggregationService`.
