# Test Scenario Guide: Emergency Maintenance Lifecycle & Dispatch 🧪

This guide outlines the technical changes and test scenarios for the newly implemented **Emergency Maintenance Lifecycle** and **Automated Technician Dispatch** system.

---

### 1. Scenario Introduction ℹ️
The Emergency Maintenance feature is designed to automate the critical path of responding to urgent facility issues. It replaces manual dispatching with a smart **Geospatial Dispatch Engine** that selects technicians based on their current proximity to the site and their expertise with specific asset types. The system now enforces **SLA (Service Level Agreement)** compliance for both response and arrival times, ensuring high-priority incidents are addressed within contractual windows.

---

### 2. Technical Schema Changes (Detailed) 🔍

#### **Client Search & Validation**
*   **Endpoint:** `GET /api/v1/maintenance/projects/clients/search`
*   **Validation Changes:** 
    *   `q`: **Required**, String, Minimum 2 characters.
*   **Response Changes:** Returns a hierarchical JSON including `client_id`, `active_contracts`, and associated `locations` with `asset_types`.

#### **Emergency Request Submission**
*   **Endpoint:** `POST /api/v1/maintenance/requests`
*   **Validation Changes (StoreEmergencyRequestRequest):**
    *   `incident_type`: **Required**, Enum (`leak`, `power_outage`, `fire`, `full_cooling_failure`, `other`).
    *   `site_contact_phone`: **Required**, String (max 20).
    *   `asset_type_ids`: **Required**, Array of existing asset type IDs.
    *   `attachments.*.temporary_folder`: **Required** for file uploads.

#### **Visit Lifecycle Controls**
*   **Endpoint:** `POST /api/v1/maintenance/visits/{id}/pause`
    *   **New Behavior:** Sets visit status to `PAUSED`.
*   **Endpoint:** `POST /api/v1/maintenance/visits/{id}/resume`
    *   **New Behavior:** Sets visit status back to `IN_PROGRESS`.

#### **Faulted Units Reporting**
*   **Endpoint:** `POST /api/v1/maintenance/visits/{id}/faulted-units`
*   **Validation Changes (StoreFaultedUnitsRequest):**
    *   `faulted_units`: **Required**, Array (min 1).
    *   `faulted_units.*.contract_unit_id`: **Required**, validates against `mod_maintenance_project_assets`.
    *   `faulted_units.*.is_faulted`: **Required**, Boolean.

---

### 3. Why the Update? (Change Log) 🔄

| Feature | Previous Behavior | New Behavior | Benefit |
| :--- | :--- | :--- | :--- |
| **Dispatch** | Manual selection by supervisors. | **Automated Haversine-based** proximity dispatch. | Reduced response time. |
| **SLA Tracking** | No real-time visibility on breaches. | **Live SLA Monitoring** via dedicated endpoint. | Contractual compliance. |
| **Visit State** | Binary (Open/Closed). | **Pause/Resume** capability. | Accurate "Time on Site" metrics. |
| **Technician Visibility**| Phone calls to check location. | **Live GPS Map** of active/paused technicians. | Improved logistics. |

---

### 4. API Endpoints Table 📊

| Process | Endpoint | Method | Description |
| :--- | :--- | :--- | :--- |
| **Technician Map** | `/api/v1/maintenance/emergency/technicians-map` | `GET` | Returns live location and status of technicians. |
| **SLA Status** | `/api/v1/maintenance/requests/{id}/sla-status` | `GET` | Calculates remaining time/breaches for a request. |
| **Client Search** | `/api/v1/maintenance/projects/clients/search` | `GET` | Optimized search for clients with active contracts. |
| **Pause Visit** | `/api/v1/maintenance/visits/{id}/pause` | `POST` | Halts the current visit timer. |
| **Resume Visit** | `/api/v1/maintenance/visits/{id}/resume` | `POST` | Restarts a paused visit. |
| **Faulted Units** | `/api/v1/maintenance/visits/{id}/faulted-units` | `POST` | Logs specific unit failures during execution. |

---

### 5. Test Cases 🧪

#### **[Case 1] The Happy Path: Emergency Auto-Dispatch**
1.  **Search:** Perform a GET search for a client with an active contract.
2.  **Create:** Submit an Emergency Request with valid `incident_type` and `asset_type_ids`.
3.  **Verify Dispatch:** Check that the system automatically identified the nearest technician and created a `SCHEDULED` visit.
4.  **Notification:** Ensure the technician received a `VisitDispatchedNotification` with the `high_priority` flag set to `true`.
5.  **Lifecycle:** Arrive at site, pause for 10 minutes, resume, and record 1 faulted unit.

#### **[Case 2] Backward Compatibility**
1.  **Legacy Visits:** Access a visit created before this update.
2.  **Verification:** Ensure the visit still loads and that pausing/resuming is available (if the status allows) without crashing due to missing `incident_type` on old records.

#### **[Case 3] Edge Cases & Constraints**
1.  **No Technicians Available:** Create an emergency request when all technicians are busy or outside range.
    *   *Expected:* `needs_manual_assignment` flag set to `true`.
2.  **Validation Failure:** Attempt to search for a client using a single character (`q=a`).
    *   *Expected:* `422 Unprocessable Entity`.
3.  **SLA Breach:** Manually update a visit's `confirmed_at` to be past the `response_deadline`.
    *   *Expected:* `sla-status` endpoint returns `is_response_breached: true`.
4.  **Double Pause:** Attempt to pause a visit that is already in `PAUSED` status.
    *   *Expected:* Logic should prevent redundant state transitions.

---
**Technical Note:** All coordinate calculations use the Haversine formula to determine the shortest distance over the earth's surface between the technician's last known location and the site.
