/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { workflow } from '../workflow-generator.js';
export function generateHealthWorkflows(version) {
    return {
        'care-plan-setup.md': workflow(version, 'Care Plan Setup', `
## 1. Gather Requirements

Ask:
- **Care plan types:** What types of care plans does the organization manage? (Chronic disease, post-acute, behavioral health, preventive)
- **Goal categories:** What goal types are tracked? (Clinical outcomes, behavioral targets, social determinants, patient education)
- **Activity types:** What activities belong to care plans? (Appointments, assessments, medication adherence, referrals, lab orders)
- **Care team composition:** Who participates? (PCP, specialist, care coordinator, social worker, patient/caregiver)
- **Template reuse:** Should care plan templates be reusable across patient populations or programs?
- **Milestone tracking:** Are there program-level milestones that trigger escalation or graduation?

Check \`force-app/main/default/objects/CarePlan*/\` and \`force-app/main/default/objects/CareProgram*/\` for existing customizations before adding new fields.

## 2. Configure Care Plan Templates

### Care Plan Structure
- \`CarePlan\` is the parent record linked to the patient Account (PersonAccount).
- Each plan contains \`CarePlanGoal\` records representing clinical or behavioral targets.
- Each goal contains \`CarePlanActivity\` records representing tasks, appointments, or interventions.
- Link the care plan to a \`CareProgram\` if the patient is enrolled in a structured program.

### Template Configuration
1. Define Care Plan Record Types for each plan category (e.g., \`Chronic_Disease\`, \`Post_Acute\`, \`Behavioral_Health\`).
2. Create page layouts per Record Type with relevant goal and activity related lists.
3. Configure path/guidance for care plan stages (Draft → Active → Completed → Closed).
4. Set up Care Plan quick actions: Add Goal, Add Activity, Assign Care Team Member.

## 3. Configure Goals and Activities

### Goals Setup
1. Define goal Record Types or picklist values for \`CarePlanGoal\` (e.g., Clinical, Behavioral, Social).
2. Configure goal status picklist: Not Started → In Progress → Achieved → Not Achieved.
3. Set target date and measurement fields for outcome tracking.
4. Link goals to \`HealthCondition\` records where applicable.

### Activities Setup
1. Define activity types via picklist: Appointment, Assessment, Medication, Education, Referral.
2. Configure activity status: Scheduled → In Progress → Completed → Cancelled.
3. Set up activity assignment rules — default owner based on activity type and care team role.
4. Enable activity reminders and overdue notifications via Flow.

## 4. Care Team Configuration

1. Use \`CareTeamMember\` to link providers, coordinators, and caregivers to the care plan.
2. Define team member roles: Primary Care Provider, Specialist, Care Coordinator, Social Worker, Caregiver.
3. Configure sharing rules so care team members have access to the patient record and care plan.
4. Set up notifications when care plan activities are assigned to team members.

## 5. Deploy Care Plan Metadata

\`\`\`bash
sf project deploy start \\
  --source-dir force-app/main/default/objects/CarePlan \\
  --source-dir force-app/main/default/objects/CarePlanGoal \\
  --source-dir force-app/main/default/objects/CarePlanActivity \\
  --source-dir force-app/main/default/objects/CareProgram \\
  --target-org <alias>
\`\`\`

Verify in the target org:
- Care plan templates render with correct goals and activities
- Care team members appear on the care plan related list
- Activity assignments route to the correct team member
- Goal status transitions trigger expected automations
`),
        'ehr-integration-setup.md': workflow(version, 'EHR Integration Setup', `
## 1. Gather EHR System Details

Ask:
- **EHR system:** Which EHR system is the source? (Epic, Cerner/Oracle Health, Allscripts, athenahealth, custom)
- **Integration pattern:** Real-time (HL7 FHIR REST), batch (file-based), or event-driven (HL7 v2 messages)?
- **FHIR version:** R4 (preferred) or STU3?
- **Data scope:** Which FHIR resources are in scope? (Patient, Encounter, Condition, MedicationRequest, Observation, AllergyIntolerance, Procedure)
- **Direction:** Inbound only (EHR → Salesforce), outbound (Salesforce → EHR), or bidirectional?
- **Authentication:** OAuth 2.0, SMART on FHIR, mutual TLS, or API key?
- **Volume:** Expected daily record volume and peak throughput requirements.

## 2. FHIR Resource Mapping

### Map FHIR Resources to Health Cloud Objects

| FHIR Resource | Health Cloud Object | Key Fields |
|---------------|--------------------| -----------|
| Patient | Account (PersonAccount) | MRN, Name, DOB, Gender, Address |
| Encounter | ClinicalEncounter | Type, Status, Period, Provider |
| Condition | HealthCondition | Code (ICD-10), ClinicalStatus, OnsetDate |
| MedicationRequest | MedicationStatement | Medication, Dosage, Status, Prescriber |
| Observation | DiagnosticSummary | Code (LOINC), Value, EffectiveDate |
| AllergyIntolerance | HealthCondition (Allergy type) | Substance, Reaction, Severity |
| Procedure | ClinicalEncounter (Procedure type) | Code (CPT), PerformedDate, Outcome |

### Clinical Data Model (CDM) Alignment
- Health Cloud CDM aligns with FHIR R4 — use CDM objects as the target for mapped resources.
- Preserve source system identifiers in \`SourceSystemIdentifier\` fields for reconciliation.
- Map coding systems: ICD-10 for conditions, LOINC for observations, CPT for procedures, RxNorm for medications.

## 3. Configure Data Sync

### Named Credentials Setup
1. Create a Named Credential for the EHR FHIR endpoint.
2. Configure authentication (OAuth 2.0 Client Credentials or SMART on FHIR).
3. Set callout endpoint: \`https://<ehr-host>/fhir/R4/\`.
4. Test connectivity with a simple \`GET /metadata\` (FHIR CapabilityStatement).

### Integration Architecture
- **Real-time (preferred):** Apex REST endpoints receive FHIR bundles; parse and upsert to CDM objects.
- **Batch:** Scheduled Apex or MuleSoft polling the EHR bulk export endpoint (\`$export\`).
- **Event-driven:** Platform Events for HL7 v2 ADT messages; trigger Flows to update patient records.

### Error Handling
- Log failed records to a custom \`Integration_Error__c\` object with FHIR resource type, ID, and error detail.
- Implement retry logic with exponential backoff for transient failures.
- Alert care coordinators when patient-critical data (allergies, medications) fails to sync.

## 4. Data Governance

### Patient Matching
- Use MRN (Medical Record Number) as the primary external ID for upsert operations.
- Implement duplicate detection rules: MRN + DOB + Last Name for probabilistic matching.
- Never auto-merge patient records — flag duplicates for manual review by Health Information Management.

### PHI Protection
- Encrypt all PHI fields at rest using Shield Platform Encryption.
- Apply field-level security: restrict clinical data fields to care team Permission Sets only.
- Enable Field Audit Trail for all CDM objects to track access and modifications.
- Log all integration data exchanges in a HIPAA-compliant audit object.

## 5. Deploy Integration Metadata

\`\`\`bash
sf project deploy start \\
  --source-dir force-app/main/default/namedCredentials \\
  --source-dir force-app/main/default/classes/*FHIR* \\
  --source-dir force-app/main/default/classes/*EHR* \\
  --source-dir force-app/main/default/customMetadata \\
  --target-org <alias>
\`\`\`

Verify in the target org:
- Named Credential authenticates successfully to the EHR endpoint
- Test FHIR resource retrieval returns expected patient data
- Mapped records appear correctly in Health Cloud patient timeline
- Error logging captures and surfaces failed sync attempts
`),
    };
}
//# sourceMappingURL=health.js.map