/*
 * 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 { generateIndustriesWorkflows } from '../generators/workflows/industries.js';
import { consultativeDesign, deployment, documentationStandards, fieldPermissionSetProtocol, flsAndCrudEnforcement, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, nativeConfigurationFirst, salesforceReferences, semanticCommits, testCoverageStandards, } from './shared-sections.js';
export const industriesProfile = {
    id: 'industries',
    label: 'Salesforce Industries Cloud (Platform)',
    ruleFile: 'industries-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)) {
            try {
                const entries = readdirSync(objectsDir);
                if (entries.some((e) => e.startsWith('vlocity_cmt__') ||
                    e.startsWith('omnistudio__') ||
                    e === 'ActionPlanTemplate' ||
                    e === 'BusinessMilestone')) {
                    return true;
                }
            }
            catch {
                // directory not readable
            }
        }
        if (existsSync(join(cwd, '.vlocity'))) {
            return true;
        }
        const omniDir = join(cwd, 'force-app/main/default/omniScripts');
        if (existsSync(omniDir)) {
            return true;
        }
        return false;
    },
    workflows: generateIndustriesWorkflows,
    ruleContent() {
        return [
            '---',
            'description: Salesforce Industries Cloud Platform Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# Salesforce Industries Cloud Platform Standards',
            '',
            '> Role: Industries Cloud Developer / Consultant — Salesforce Professional Services.',
            '> Industries Cloud is the shared platform underlying vertical clouds (Communications, Health, FSC, etc.).',
            '> It provides OmniStudio, Industries Order Management, Action Plans, Decision Tables, and Document Generation.',
            '> All standards here apply **in addition to** general Apex and LWC rules.',
            '',
            ...consultativeDesign('Industries Cloud platform decisions, OmniStudio architecture, and order management'),
            '',
            ...nativeConfigurationFirst(),
            '',
            '## Industries Cloud Platform Architecture',
            '',
            '### Namespace Strategy',
            '- **`vlocity_cmt__`** — Legacy Vlocity managed package namespace (pre-unification installations).',
            '- **`omnistudio__`** — Standard OmniStudio namespace for newer installations.',
            '- **No namespace** — Industries common objects (ActionPlanTemplate, BusinessMilestone, DecisionTable).',
            '- Determine which namespace applies at project start and document it. Never mix namespaces in the same org.',
            '',
            '### Package Dependency Chain',
            '- Industries packages depend on OmniStudio (standard or managed).',
            '- Always verify package version compatibility before upgrades.',
            '- Run `sf package installed list` to audit the current state before any metadata changes.',
            '',
            '## OmniStudio Components',
            '',
            '### OmniScripts',
            '- Guided experiences for complex multi-step processes (onboarding, ordering, claims).',
            '- Keep OmniScripts thin: delegate data logic to Integration Procedures or DataRaptors.',
            '- Version management: develop on new version, keep active version stable.',
            '- Never embed SOQL or DML directly — use DataRaptors for all object I/O.',
            '',
            '### DataRaptors',
            '- **Extract:** Read Salesforce data into JSON for OmniScript consumption.',
            '- **Transform:** Reshape data between systems without DML (pure mapping).',
            '- **Load:** Write data back to Salesforce objects with field-level mapping.',
            '- Prefer DataRaptors over Apex for standard CRUD within OmniStudio flows.',
            '- Test DataRaptors with various record counts to ensure bulkification.',
            '',
            '### Integration Procedures',
            '- Server-side orchestration of multiple DataRaptors, Apex actions, and HTTP callouts.',
            '- Use Integration Procedures (not Apex) as the backing for OmniScript remote actions.',
            '- Keep Integration Procedures reusable — parameterize inputs, avoid hardcoded IDs.',
            '- Test with `Test Integration Procedure` action in OmniStudio Designer.',
            '',
            '### FlexCards',
            '- Contextual UI components for record pages, portals, and Experience Cloud.',
            '- Data sources: DataRaptors, SOSL, Apex Remote, or Integration Procedures.',
            '- Keep FlexCards lightweight — delegate complex logic to backing data sources.',
            '- Use conditional visibility for dynamic content based on record state.',
            '',
            '## Industries Order Management',
            '',
            '### Order Decomposition',
            '- Commercial order (customer-facing) decomposes into fulfillment orders (system-facing).',
            '- Decomposition rules define how line items split by service type, network element, or billing system.',
            '- Action codes: Add (new), Modify (change), Delete (disconnect), NoChange (context only).',
            '- Test decomposition with representative orders for all product types.',
            '',
            '### Orchestration Plans',
            '- Define fulfillment step sequences (sequential or parallel) per order type.',
            '- Step types: Auto (API callout), Manual (human task), Event (Platform Event), Sub-orchestration.',
            '- Set completion criteria, timeout, and retry policies per step.',
            '- Plans are reusable across order types — parameterize with order attributes.',
            '',
            '### Fallout Handling',
            '- Define retry policies per step: max retries, exponential backoff.',
            '- Escalation path: assign to fallout queue after retries exhausted.',
            '- Compensating actions: rollback previously completed steps when order cannot proceed.',
            '- Monitor with dashboards tracking order pipeline health and SLA adherence.',
            '',
            '## Industries Common Objects',
            '',
            '### Action Plans',
            '- `ActionPlanTemplate` + `ActionPlanTemplateItem`: Step-by-step process templates.',
            '- Auto-generate Action Plans on record creation via triggers or flows.',
            '- Track step completion, dependencies, and due dates.',
            '',
            '### Decision Tables',
            '- `DecisionTable`: Tabular business rules for pricing, eligibility, routing.',
            '- Prefer Decision Tables over Apex logic for rules that change frequently.',
            '- Version Decision Tables: clone before modifying active versions.',
            '',
            '### Document Generation',
            '- Industries Document Generation for contracts, proposals, compliance documents.',
            '- Use merge fields mapped to the source record and related data.',
            '- Test document output with representative data before deploying templates.',
            '',
            '## Managed Package Safety',
            '- **Do NOT add Apex triggers on managed objects** (`vlocity_cmt__*`, `omnistudio__*`).',
            '  Use Record-Triggered Flows or custom extension objects.',
            '- **Do NOT delete or rename managed fields.** Extend only with project-prefixed custom fields.',
            '- **Do NOT override managed page layouts.** Clone and assign to your Record Type.',
            '- Before package upgrades, review release notes for breaking changes.',
            '- Test upgrades in sandbox with full regression before production.',
            '',
            '## TMF Standards Alignment',
            '- TMF620 (Product Catalog): ProductOffering → ProductSpecification → Attributes.',
            '- TMF622 (Product Ordering): Order lifecycle states — acknowledged → inProgress → completed/failed.',
            '- TMF641 (Service Ordering): Fulfillment-side lifecycle — map orchestration step statuses to TMF states.',
            '- Expose APIs aligned with TMF resource models for external system interoperability.',
            '',
            ...deployment(),
            '',
            ...semanticCommits(),
            '',
            ...salesforceReferences(),
            '',
            ...generatedPromptsProtocol(),
            '',
            ...testCoverageStandards(),
            '',
            ...fieldPermissionSetProtocol(),
            '',
            ...flsAndCrudEnforcement(),
            '',
            ...documentationStandards(),
            '',
            '## Industries Cloud References',
            '- Industries Common Features: https://developer.salesforce.com/docs/atlas.en-us.industries_reference.meta/industries_reference/',
            '- OmniStudio Developer Guide: https://developer.salesforce.com/docs/atlas.en-us.omnistudio.meta/omnistudio/',
            '- Industries Order Management: https://developer.salesforce.com/docs/atlas.en-us.industries_order_management.meta/industries_order_management/',
            '- Action Plans: https://help.salesforce.com/s/articleView?id=sf.fsc_action_plans.htm',
            '',
            ...getSharedSectionLines('industries'),
            '',
            ...interactionPreferences('Industries Cloud platform architecture and OmniStudio components'),
        ].join('\n');
    },
};
//# sourceMappingURL=industries.js.map