/*
 * 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 { existsSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import { generateHealthWorkflows } from '../generators/workflows/health.js';
import { consultativeDesign, deployment, documentationStandards, flsAndCrudEnforcement, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, nativeConfigurationFirst, salesforceReferences, semanticCommits, testCoverageStandards, } from './shared-sections.js';
export const healthProfile = {
    id: 'health',
    label: 'Health Cloud',
    ruleFile: 'health-standards.mdc',
    extensions: ['salesforce.salesforcedx-vscode'],
    capabilities: ['deploy', 'code-analysis', 'prompt-registry', 'declare-points'],
    cursorScope: 'description',
    detect(cwd) {
        const objectsDir = join(cwd, 'force-app/main/default/objects');
        if (!existsSync(objectsDir))
            return false;
        // Check for HealthCloudGA__ prefix objects
        try {
            const entries = readdirSync(objectsDir);
            if (entries.some((e) => e.startsWith('HealthCloudGA__')))
                return true;
        }
        catch {
            // directory not readable — fall through
        }
        return existsSync(join(objectsDir, 'CarePlan')) || existsSync(join(objectsDir, 'CareProgram'));
    },
    workflows: generateHealthWorkflows,
    ruleContent() {
        return [
            '---',
            'description: Health Cloud Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# Health Cloud Standards',
            '',
            '> Role: Health Cloud Developer / Consultant — Salesforce Professional Services.',
            '> Health Cloud is a managed package on top of core Salesforce. All standards here apply **in addition to** general Apex and LWC rules.',
            '',
            ...consultativeDesign('Health Cloud data model and clinical configuration decisions'),
            '',
            ...nativeConfigurationFirst(),
            '',
            '## Health Cloud Data Model (CRITICAL)',
            '',
            '### Patient / Member Model',
            '- **PersonAccount for patients/members.** Enable PersonAccount in Setup → Account Settings.',
            '  Use a dedicated Record Type (e.g., `Patient`, `Member`) — never share a Record Type between patient and provider accounts.',
            '- **Provider accounts** use Business Account Record Types (e.g., `Health_Care_Provider`, `Health_Care_Facility`).',
            '- **Never create a custom "patient" object.** The Health Cloud patient model uses PersonAccount as the system of record.',
            '',
            '### Core Health Cloud Objects',
            '| Object | API Name | Purpose |',
            '|--------|----------|---------|',
            '| Account (Patient) | `Account` (PersonAccount) | Patient/Member demographic record |',
            '| Care Plan | `CarePlan` | Treatment plan linking goals, activities, and care team |',
            '| Care Plan Goal | `CarePlanGoal` | Clinical/behavioral target within a care plan |',
            '| Care Plan Activity | `CarePlanActivity` | Task or intervention to achieve a goal |',
            '| Care Program | `CareProgram` | Structured program (e.g., Chronic Disease Management) |',
            '| Care Program Enrollee | `CareProgramEnrollee` | Patient enrollment in a care program |',
            '| Clinical Encounter | `ClinicalEncounter` | Patient visit or interaction record |',
            '| Health Condition | `HealthCondition` | Diagnosis, allergy, or clinical condition |',
            '| Medication Statement | `MedicationStatement` | Active/historical medication record |',
            '| Diagnostic Summary | `DiagnosticSummary` | Lab results, vital signs, observations |',
            '',
            '## Patient 360',
            '- **Timeline components:** Use the Health Cloud Patient Timeline component to display clinical encounters,',
            '  conditions, medications, and care plan activities in chronological order.',
            '- **Care team composition:** Display care team members (PCP, specialist, coordinator, caregiver) on the',
            '  patient record using the Care Team related list and Care Team Member object.',
            '- **Social determinants:** Track social determinants of health (SDOH) using `HealthCondition` records',
            '  with appropriate category coding (Z-codes from ICD-10) or dedicated SDOH assessment objects.',
            '- Configure the Patient Card (compact layout) to show: MRN, DOB, Primary Condition, Care Program enrollment status.',
            '',
            '## Care Management',
            '',
            '### Care Plan Templates',
            '- Define reusable care plan templates with pre-configured goals and activities per condition or program.',
            '- Use Record Types on `CarePlan` to distinguish plan categories (Chronic, Post-Acute, Behavioral, Preventive).',
            '- Templates should include default care team roles, goal targets, and activity schedules.',
            '',
            '### Goals and Activities Tracking',
            '- Goals track clinical outcomes with target values and dates (`CarePlanGoal`).',
            '- Activities represent discrete interventions: appointments, assessments, education, medication tasks (`CarePlanActivity`).',
            '- Automate activity creation from goal templates using Record-Triggered Flows.',
            '- Status progression: Not Started → In Progress → Achieved/Not Achieved (goals), Scheduled → Completed → Cancelled (activities).',
            '',
            '### Program Enrollment and Milestones',
            '- `CareProgram` defines the program structure (eligibility criteria, duration, milestones).',
            '- `CareProgramEnrollee` tracks individual patient enrollment, start date, and status.',
            '- Define program milestones (e.g., 30-day check-in, 90-day reassessment) as activities or custom milestone records.',
            '- Trigger graduation or escalation flows based on milestone completion or missed targets.',
            '',
            '## EHR Integration',
            '',
            '### FHIR R4 Data Model Alignment',
            '- Health Cloud Clinical Data Model (CDM) aligns with HL7 FHIR R4 resource types.',
            '- Map FHIR resources to Health Cloud objects: Patient → Account, Encounter → ClinicalEncounter,',
            '  Condition → HealthCondition, MedicationRequest → MedicationStatement, Observation → DiagnosticSummary.',
            '- Preserve source system identifiers for reconciliation and bidirectional sync.',
            '',
            '### HL7 Integration Patterns',
            '- **Real-time:** FHIR REST APIs via Named Credentials; Apex REST endpoints for inbound bundles.',
            '- **Batch:** Scheduled jobs polling EHR bulk export (`$export`) endpoints.',
            '- **Event-driven:** Platform Events for HL7 v2 ADT/ORU messages; Flow subscribers update patient records.',
            '- Use MuleSoft Healthcare Accelerator for complex transformation and routing scenarios.',
            '',
            '### Clinical Data Model (CDM)',
            '- CDM objects are the canonical store for clinical data in Health Cloud.',
            '- Map coding systems: ICD-10 (conditions), LOINC (observations), CPT (procedures), RxNorm (medications).',
            '- Never create custom clinical objects that duplicate CDM coverage — extend CDM objects with custom fields if gaps exist.',
            '',
            '## Utilization Management',
            '- **Prior authorization:** Use `CareRequest` and `CareRequestItem` for authorization workflows.',
            '- **Service requests:** Track requested services, approvals, and denials with status lifecycle.',
            '- **Review workflows:** Implement clinical review decision trees using Flows or OmniStudio guided processes.',
            '- Automate authorization expiration alerts and renewal reminders.',
            '',
            '## Provider Management',
            '- **Provider search:** Use provider Account records with specialties, locations, and network participation.',
            '- **Referral management:** Track referrals between providers using standard referral objects or custom processes.',
            '- **Network adequacy:** Monitor provider availability by specialty, geography, and language to meet regulatory requirements.',
            '- Link providers to care teams via `CareTeamMember` with defined roles.',
            '',
            '## HIPAA Compliance (CRITICAL)',
            '',
            '### PHI Protection',
            '- **Field-level encryption:** Enable Shield Platform Encryption for all PHI fields',
            '  (SSN, MRN, DOB, clinical notes, diagnosis codes, medication details).',
            '- **Audit trail:** Enable Field Audit Trail on all CDM objects and patient Account fields.',
            '  Retain audit data for minimum 6 years per HIPAA requirements.',
            '- **Minimum necessary access:** Grant access to clinical data only to users who need it for their role.',
            '  Use Permission Sets scoped to care team membership, not broad profiles.',
            '',
            '### Access Controls',
            '- **Role-based access:** Care coordinators see care plans; billing staff see claims but not clinical notes;',
            '  providers see full clinical records only for their assigned patients.',
            '- **Consent management:** Track patient consent for data sharing using consent records.',
            '  Enforce consent-based visibility rules in sharing logic.',
            '- **Break-the-glass:** Implement emergency access with mandatory justification logging for restricted PHI.',
            '',
            '### Audit Requirements',
            '- Log all PHI access (view, create, update, export) in a HIPAA-compliant audit object.',
            '- Enable Login History and Setup Audit Trail retention.',
            '- Implement automated alerts for unusual access patterns (bulk exports, off-hours access).',
            '',
            '## Managed Package Safety (HealthCloudGA Namespace)',
            '- **Do NOT add Apex triggers directly on Health Cloud managed objects** (`HealthCloudGA__*`).',
            '  Use Record-Triggered Flows or a custom extension object instead.',
            '- **Do NOT delete or rename Health Cloud managed fields.** Extend only — add custom fields with a project prefix.',
            '- **Do NOT override Health Cloud managed page layouts.** Clone them and assign the clone to your Record Type.',
            '- Before each package upgrade, review the release notes for breaking changes to CDM objects.',
            '- Test in a sandbox with a full package upgrade before promoting to production.',
            '',
            '## Security: Patient Data Sharing Model',
            '- Health Cloud uses **Care Team-based sharing** for patient record access.',
            '  Add providers and coordinators to the patient care team with appropriate roles and access levels.',
            '- **OWD for clinical objects:** Set to Private. Share via care team membership or sharing rules scoped to programs.',
            '- **Restriction Rules:** Use to limit record visibility by care program, facility, or department',
            '  without custom Apex sharing.',
            '- Health Cloud Permission Sets to assign (do not create duplicates):',
            '  - `HealthCloud` — base Health Cloud access',
            '  - `HealthCloudAdmin` — administrative features (templates, program configuration)',
            '  - `HealthCloudApi` — API access for integration users',
            '',
            '## Testing Health Cloud',
            '- **Use TestDataFactory** to create patient PersonAccounts, CarePlans, and clinical data in test setup.',
            '  Never use real PHI in test data — generate synthetic patient records with clearly fake identifiers.',
            '- PersonAccount creation requires inserting an Account with a PersonAccount Record Type Id.',
            '- Assign Health Cloud Permission Sets to test users in `@TestSetup` — `HealthCloud` is required for object access.',
            '- Test care plan workflows end-to-end: enrollment → goal creation → activity completion → milestone tracking.',
            '- Mock EHR callouts using `Test.setMock(HttpCalloutMock.class, ...)` with sample FHIR bundles.',
            '- Verify sharing rules: test that non-care-team users cannot access patient clinical data.',
            ...testCoverageStandards(),
            '',
            ...flsAndCrudEnforcement(),
            '',
            ...documentationStandards(),
            '',
            ...deployment(),
            '',
            ...semanticCommits(),
            '',
            ...generatedPromptsProtocol(),
            '',
            '## Health Cloud References',
            '- Health Cloud Developer Guide: https://developer.salesforce.com/docs/atlas.en-us.health_cloud.meta/health_cloud/',
            '- Health Cloud Object Reference: https://developer.salesforce.com/docs/atlas.en-us.health_cloud_object_reference.meta/health_cloud_object_reference/',
            '- Clinical Data Model: https://developer.salesforce.com/docs/atlas.en-us.health_cloud_cdm.meta/health_cloud_cdm/',
            '- FHIR R4 Integration: https://help.salesforce.com/s/articleView?id=sf.health_fhir_overview.htm',
            '',
            ...salesforceReferences(),
            ...getSharedSectionLines('health'),
            '',
            ...interactionPreferences('Health Cloud configuration'),
        ].join('\n');
    },
};
//# sourceMappingURL=health.js.map