# Patient Requirements Admin Service (`patient-requirements.admin.service.ts`)

## Overview

The `PatientRequirementsAdminService` is a backend service responsible for managing administrative tasks related to `PatientRequirementInstance` documents, primarily focusing on the lifecycle of associated patient notifications. This service is designed to be primarily invoked by Cloud Functions that trigger on Create, Update, and Delete events of `PatientRequirementInstance` documents in Firestore.

It ensures that patients receive timely notifications for instructions they need to follow before an appointment and that these notifications are appropriately updated or cancelled if the appointment or requirement details change.

## Core Dependencies

- **Firebase Admin SDK**: For interacting with Firestore.
- **`NotificationsAdmin` Service**: For creating, fetching, and updating notification documents.
- **Shared Types**: Uses types defined in `Api/src/types/` for `PatientRequirementInstance`, `PatientInstruction`, `Notification`, `PatientProfile`, etc., ensuring consistency across the application. This includes using client-side `Timestamp` types (`@firebase/firestore.Timestamp`) for data stored in Firestore documents that are also accessed by the client.

## Methods

### 1. `constructor(firestore?: admin.firestore.Firestore)`

- **Purpose**: Initializes the service.
- **Parameters**:
  - `firestore` (optional): An instance of `admin.firestore.Firestore`. If not provided, it initializes a new default instance.
- **Core Logic**:
  1.  Sets up the Firestore database connection (`this.db`).
  2.  Initializes an instance of the `NotificationsAdmin` service (`this.notificationsAdmin`), passing the Firestore instance to it.

### 2. `async processRequirementInstanceAndScheduleNotifications(patientId: string, instance: PatientRequirementInstance, previousInstanceData?: PatientRequirementInstance)`

- **Purpose**: This is the primary method for handling the creation and updates of a `PatientRequirementInstance`. It iterates through the instructions within the instance, schedules new notifications, cancels outdated ones, and updates the instruction statuses and notification IDs within the `PatientRequirementInstance` document.
- **Parameters**:
  - `patientId: string`: The ID of the patient to whom the requirement instance belongs.
  - `instance: PatientRequirementInstance`: The current (new or updated) data of the patient requirement instance.
  - `previousInstanceData?: PatientRequirementInstance` (optional): The state of the instance _before_ the current change. This is crucial for determining if due times have changed or if instructions were cancelled/reactivated, necessitating changes to existing notifications.
- **Core Logic Flow**:
  1.  **Fetch Patient Expo Tokens**: Retrieves the patient's Expo push notification tokens from their `PatientProfile`. If no tokens are found, notification scheduling for that patient is skipped.
  2.  **Iterate Through Instructions**: Loops through each `PatientRequirementInstruction` in the `instance.instructions` array.
      - A copy of the instructions array (`updatedInstructions`) is made to track changes without mutating the input directly.
  3.  **Handle Cancelled/Superseded Instances/Instructions**:
      - If the overall `instance.overallStatus` indicates a cancelled appointment or a superseded reschedule, or if an individual `currentInstruction.status` is `CANCELLED`:
        - If the instruction had an existing `notificationId`, calls `this.notificationsAdmin.updateNotificationStatus()` to set the notification's status to `CANCELLED`.
        - Updates the `currentInstruction`'s `notificationId` to `undefined` and its `status` to `CANCELLED`.
        - Marks that `instructionUpdatesMade` is `true`.
  4.  **Handle Reschedules/Reactivations for Existing Notifications**:
      - Compares `currentInstruction` with `previousInstruction` (if available).
      - Determines if `dueTimeChanged` or if the instruction `wasPreviouslyCancelledAndNowActive`.
      - If either is true AND the `currentInstruction` has a `notificationId` (meaning an old notification exists):
        - Cancels the old notification using `this.notificationsAdmin.updateNotificationStatus()`.
        - Clears `currentInstruction.notificationId`.
        - Marks `instructionUpdatesMade` as `true`.
  5.  **Schedule New Notifications**:
      - Checks if a notification `shouldSchedule` for the `currentInstruction`:
        - Instruction status must be `PENDING_NOTIFICATION`.
        - No existing `notificationId`.
        - `dueTime` must be in the future.
        - Patient must have Expo tokens.
      - If `shouldSchedule` is true:
        - Constructs a `notificationPayload` for a `RequirementInstructionDueNotification`.
        - Calls `this.notificationsAdmin.createNotification()` to create the notification document.
        - Updates `currentInstruction` with the new `notificationId` and ensures its status is `PENDING_NOTIFICATION`.
        - Marks `instructionUpdatesMade` as `true`.
  6.  **Update Firestore Document**:
      - If `instructionUpdatesMade` is `true` (meaning any instruction's notification details or status changed):
        - Updates the `PatientRequirementInstance` document in Firestore with the `updatedInstructions` array and sets its `updatedAt` timestamp.
        - Ensures all `updatedAt` (and other Timestamp fields) within `updatedInstructions` and for the main instance are converted to `FirebaseClientTimestamp` for compatibility with shared types.
- **Usage Context**:
  - Triggered by a Cloud Function on **create** of a `PatientRequirementInstance`.
  - Triggered by a Cloud Function on **update** of a `PatientRequirementInstance`. The Cloud Function should provide both the new and previous data of the instance.

### 3. `async cancelAllNotificationsForInstance(instance: PatientRequirementInstance)`

- **Purpose**: To cancel all _pending_ notifications associated with a given `PatientRequirementInstance`. This is typically used when an entire instance is hard-deleted or unequivocally cancelled in a way not covered by status changes processed by `processRequirementInstanceAndScheduleNotifications`.
- **Parameters**:
  - `instance: PatientRequirementInstance`: The requirement instance whose notifications need to be cancelled.
- **Core Logic Flow**:
  1.  Iterates through each instruction in `instance.instructions`.
  2.  If an instruction has a `notificationId`:
      - Fetches the notification using `this.notificationsAdmin.getNotification()`.
      - If the notification exists and its status is `PENDING`:
        - Calls `this.notificationsAdmin.updateNotificationStatus()` to set its status to `CANCELLED`.
- **Usage Context**:
  - Triggered by a Cloud Function on **delete** of a `PatientRequirementInstance`.
  - Can also be invoked if an instance's overall status changes to a terminal "cancelled" state that requires immediate cessation of all related pending notifications.

### 4. `async updateMissedInstructions(patientId: string, instanceId: string)`

- **Purpose**: (Optional utility, typically for a cron job) Scans instructions within a specific `PatientRequirementInstance` that are past their `dueTime` but have not yet been actioned (i.e., status is `PENDING_NOTIFICATION` or `ACTION_DUE`). It updates their status to `MISSED`.
- **Parameters**:
  - `patientId: string`: The ID of the patient.
  - `instanceId: string`: The ID of the `PatientRequirementInstance` to check.
- **Core Logic Flow**:
  1.  Fetches the specified `PatientRequirementInstance` document.
  2.  If not found, logs a warning and exits.
  3.  Iterates through each instruction in the instance.
  4.  If an instruction's `dueTime` is in the past AND its status is `PENDING_NOTIFICATION` or `ACTION_DUE`:
      - Updates the instruction's `status` to `MISSED`.
      - Sets the instruction's `updatedAt` timestamp (converted to `FirebaseClientTimestamp`).
      - Marks that `changesMade` is `true`.
  5.  If `changesMade` is `true`:
      - Updates the `PatientRequirementInstance` document in Firestore with the modified instructions and sets its main `updatedAt` timestamp (converted to `FirebaseClientTimestamp`).
- **Usage Context**:
  - Intended to be called by a scheduled Cloud Function (e.g., a daily cron job) to perform cleanup and status updates for instructions that were not completed by their due date.

### 5. `async updateOverallInstanceStatus(patientId: string, instanceId: string)`

- **Purpose**: Calculates and updates the `overallStatus` of a `PatientRequirementInstance` based on the collective statuses of its individual, non-cancelled instructions. This helps reflect the true completion state of the entire requirement set.
- **Parameters**:
  - `patientId: string`: The ID of the patient to whom the requirement instance belongs.
  - `instanceId: string`: The ID of the `PatientRequirementInstance` to update.
- **Core Logic Flow**:
  1.  **Fetch Instance**: Retrieves the specified `PatientRequirementInstance`.
  2.  **Check Terminal States**: If the current `instance.overallStatus` is already `CANCELLED_APPOINTMENT`, `SUPERSEDED_RESCHEDULE`, or `FAILED_TO_PROCESS`, the function logs this and exits, as these are considered final states not to be overridden by this logic.
  3.  **Handle No Active Instructions**: Filters out any instructions with a status of `CANCELLED`. If no non-cancelled instructions remain:
      - Sets the `overallStatus` to `ACTIVE` (if not already) and updates Firestore. This acts as a default if an instance becomes empty of actionable items.
  4.  **Check for Pending/Due Instructions**: Iterates through the non-cancelled instructions. If any instruction has a status of `PENDING_NOTIFICATION` or `ACTION_DUE`:
      - The `newOverallStatus` is determined to be `ACTIVE`.
  5.  **All Instructions Resolved**: If no instructions are `PENDING_NOTIFICATION` or `ACTION_DUE` (meaning all non-cancelled instructions are in a "resolved" state: `ACTION_TAKEN`, `MISSED`, or `SKIPPED`):
      - Counts `effectivelyCompletedCount` (non-cancelled instructions that are `ACTION_TAKEN` or `SKIPPED`).
      - Calculates `completionPercentage = (effectivelyCompletedCount / totalNonCancelledInstructions) * 100`.
      - If `completionPercentage === 100%`, `newOverallStatus` is `ALL_INSTRUCTIONS_MET`.
      - Else if `completionPercentage >= 60%`, `newOverallStatus` is `PARTIALLY_COMPLETED`.
      - Else (`completionPercentage < 60%`), `newOverallStatus` is `FAILED_TO_PROCESS`.
  6.  **Update Firestore**: If the calculated `newOverallStatus` is different from the `instance.overallStatus` currently in Firestore, it updates the document with the new status and the current timestamp (converted to `FirebaseClientTimestamp`).
- **Usage Context**:
  - Typically called by a Cloud Function triggered on **update** of a `PatientRequirementInstance`, ideally after `processRequirementInstanceAndScheduleNotifications` (or any other logic that might modify individual instruction statuses) has completed. This ensures the `overallStatus` accurately reflects the latest state of the instructions.
  - It helps maintain data integrity and provides a clear, high-level status for the entire set of requirements.

## Timestamp Handling

A key aspect of this service is the correct handling of Firestore Timestamps. Since the shared type definitions (e.g., for `PatientRequirementInstruction`) expect Timestamps compatible with the client-side Firebase SDK (`@firebase/firestore.Timestamp`), any Timestamps generated by the Admin SDK (e.g., `admin.firestore.Timestamp.now()`) must be converted to `new FirebaseClientTimestamp(adminTimestamp.seconds, adminTimestamp.nanoseconds)` before being written back to Firestore as part of these shared types. This ensures type consistency across the backend (admin) and frontend/shared type definitions.
