# Practitioner Aggregation Service (Admin)

This service centralizes the logic for updating aggregated data in various Firestore collections _when a practitioner is created, updated, or deleted_. It is designed primarily for use by Cloud Functions triggered by changes in the `practitioners` collection.

## `PractitionerAggregationService` Class

### Constructor

```typescript
constructor(firestore?: admin.firestore.Firestore)
```

Initializes the service with an Admin Firestore instance. Uses the default instance if none is provided.

### Methods Triggered by Practitioner **Creation**

- **`addPractitionerToClinic(clinicId: string, doctorInfo: DoctorInfo): Promise<void>`**
  - Adds the `practitionerId` (from `doctorInfo.id`) and the `doctorInfo` object to the `doctors` and `doctorsInfo` arrays respectively in the specified `Clinic` document.
  - Typically called for each clinic the new practitioner is associated with.

### Methods Triggered by Practitioner **Update**

- **`updatePractitionerInfoInClinics(clinicIds: string[], doctorInfo: DoctorInfo): Promise<void>`**
  - Updates the aggregated `doctorsInfo` array within multiple `Clinic` documents associated with the practitioner.
  - Uses a batch write to first remove the old `DoctorInfo` (matching by `id`) and then add the updated `doctorInfo`.
- **`updatePractitionerInfoInProcedures(procedureIds: string[], doctorInfo: DoctorInfo): Promise<void>`**
  - Updates the embedded `doctorInfo` object within multiple `Procedure` documents associated with the updated practitioner.
- **`updatePractitionerInfoInCalendarEvents(practitionerId: string, practitionerInfo: DoctorInfo): Promise<void>`**
  - Uses a Collection Group query (`calendar` subcollection) to find all _upcoming_ calendar events associated with the `practitionerId`.
  - Updates the embedded `practitionerInfo` object in these calendar events.

### Methods Triggered by Practitioner **Deletion**

- **`removePractitionerFromClinics(clinicIds: string[], practitionerId: string): Promise<void>`**
  - Removes the `practitionerId` from the `doctors` array and the corresponding `DoctorInfo` object (matching by `id`) from the `doctorsInfo` array in multiple `Clinic` documents.
- **`cancelUpcomingCalendarEventsForPractitioner(practitionerId: string): Promise<void>`**
  - Uses a Collection Group query (`calendar` subcollection) to find all _upcoming_ calendar events associated with the `practitionerId`.
  - Sets the `status` of these events to `CANCELED` and adds a `cancelReason` ("Practitioner deleted").
- **`removePractitionerFromPatients(patientIds: string[], practitionerId: string): Promise<void>`**
  - Removes the `practitionerId` from the `doctorIds` array in multiple `Patient` documents.
- **`inactivateProceduresForPractitioner(procedureIds: string[]): Promise<void>`**
  - Sets the `isActive` flag to `false` for multiple `Procedure` documents associated with the deleted practitioner.
