/*
 * 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 { generateCommunicationsWorkflows } from '../generators/workflows/communications.js';
import { consultativeDesign, deployment, documentationStandards, flsAndCrudEnforcement, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, nativeConfigurationFirst, salesforceReferences, semanticCommits, testCoverageStandards, } from './shared-sections.js';
export const communicationsProfile = {
    id: 'communications',
    label: 'Communications Cloud',
    ruleFile: 'communications-standards.mdc',
    extensions: ['salesforce.salesforcedx-vscode'],
    capabilities: ['deploy', 'code-analysis', 'prompt-registry', 'declare-points'],
    cursorScope: 'description',
    detect(cwd) {
        // Check for vlocity_cmt__ prefix objects
        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__'))) {
                    return true;
                }
            }
            catch {
                // directory not readable — fall through
            }
        }
        // Check for OrderItem with telecom fields (presence of OrderItem object in a Vlocity context)
        if (existsSync(join(objectsDir, 'OrderItem'))) {
            try {
                const orderItemFields = readdirSync(join(objectsDir, 'OrderItem/fields'));
                if (orderItemFields.some((f) => f.startsWith('vlocity_cmt__'))) {
                    return true;
                }
            }
            catch {
                // no fields dir — fall through
            }
        }
        // Check for .vlocity directory
        if (existsSync(join(cwd, '.vlocity'))) {
            return true;
        }
        return false;
    },
    workflows: generateCommunicationsWorkflows,
    ruleContent() {
        return [
            '---',
            'description: Communications Cloud (Telco) Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# Communications Cloud (Telco) Standards',
            '',
            '> Role: Communications Cloud Developer / Consultant — Salesforce Professional Services.',
            '> Communications Cloud (Industries CPQ + Order Management) is a managed package built on Vlocity.',
            '> All standards here apply **in addition to** general Apex and LWC rules.',
            '',
            ...consultativeDesign('Communications Cloud data model, product catalog, and order orchestration decisions'),
            '',
            ...nativeConfigurationFirst(),
            '',
            '## Communications Cloud Data Model (CRITICAL)',
            '',
            '### Core Concepts',
            '- **Industries CPQ (Vlocity):** Product catalog, guided selling, cart management, pricing, and quoting.',
            '- **Order Management:** Order decomposition, orchestration plans, fulfillment steps, and fallout handling.',
            '- **Service Qualification:** Network availability checks before order submission.',
            '- **Network/Asset Inventory:** Tracking physical and logical network assets, service points, and CPE.',
            '',
            '### Key Objects',
            '| Object | API Name | Purpose |',
            '|--------|----------|---------|',
            '| Product Offering | `vlocity_cmt__ProductOffering__c` | Sellable product visible to customers (plans, bundles) |',
            '| Product Specification | `vlocity_cmt__ProductSpecification__c` | Technical blueprint defining product characteristics |',
            '| Order Item | `OrderItem` (with decomposition fields) | Line item decomposed into fulfillment orders |',
            '| Service Resource | `ServiceResource` | Technician or asset available for field operations |',
            '| Network Asset | `vlocity_cmt__NetworkAsset__c` | Physical/logical network element (port, slot, card) |',
            '| Billing Account | `vlocity_cmt__BillingAccount__c` | Customer billing entity linked to payment methods |',
            '| Orchestration Plan | `vlocity_cmt__OrchestrationPlan__c` | Defines fulfillment step sequence for order execution |',
            '| Orchestration Item | `vlocity_cmt__OrchestrationItem__c` | Individual step within an orchestration plan |',
            '',
            '## Industries CPQ — Product Catalog',
            '',
            '### Catalog Structure',
            '- **ProductOffering → ProductSpecification → Attributes** is the canonical hierarchy.',
            '- ProductOffering is the sellable entity (what the customer sees).',
            '- ProductSpecification is the technical blueprint (reusable across offerings).',
            '- Attributes define configurable properties (bandwidth, contract term, SIM type).',
            '- Use `vlocity_cmt__ProductOfferingSpecRelationship__c` to link offerings to specifications.',
            '',
            '### Pricing',
            '- **One-Time Charge (OTC):** activation fees, installation, equipment purchase.',
            '- **Recurring Charge (RC):** monthly subscription, equipment rental, service fees.',
            '- **Usage Charge:** per-unit overage (data, minutes, SMS), pay-per-view.',
            '- Pricing is modeled via `vlocity_cmt__PricingElement__c` linked to offerings.',
            '- Support pricing tiers, volume discounts, and effective date ranges.',
            '',
            '### Promotions and Discounts',
            '- Promotions link to offerings with eligibility criteria (new customer, upgrade, loyalty).',
            '- Discount types: percentage, fixed amount, free period, waived fee.',
            '- Promotions have effective dates and auto-expiry — never create open-ended promotions without business justification.',
            '- Validate stacking rules: which promotions can combine and which are mutually exclusive.',
            '',
            '## Order Management',
            '',
            '### Order Decomposition',
            '- A commercial order (customer-facing) decomposes into fulfillment orders (system-facing).',
            '- Decomposition rules in `vlocity_cmt__DecompositionRelationship__c` define how line items split.',
            '- Each fulfillment order targets a specific domain: network, billing, inventory, or field service.',
            '- Complex bundles (e.g., triple-play) decompose into multiple domain-specific fulfillment orders.',
            '',
            '### Orchestration Plans',
            '- Plans define the sequence of fulfillment steps (sequential or parallel).',
            '- Step types: Auto (API callout), Manual (human task), Event (Platform Event), Sub-orchestration.',
            '- Each step has completion criteria, timeout, and fallout rules.',
            '- Plans are reusable across order types — parameterize with order attributes.',
            '',
            '### Fulfillment Steps',
            '- Each step maps to a concrete action: provision network port, activate SIM, ship CPE, update billing.',
            '- Steps publish/consume Platform Events for async system integration.',
            '- Implement idempotent fulfillment actions — retries must not create duplicate resources.',
            '',
            '### Order Fallout Handling',
            '- Define retry policy per step: max retries, backoff interval.',
            '- Escalation path: assign to fallout queue after max retries exceeded.',
            '- Compensating actions: rollback previously completed steps when order cannot proceed.',
            '- Log all fallout events for operational reporting and SLA tracking.',
            '',
            '## TMF (TeleManagement Forum) Alignment',
            '',
            '### TMF620 — Product Catalog Management',
            '- ProductOffering and ProductSpecification align with TMF620 entities.',
            '- Attribute schema should follow TMF characteristic value specification patterns.',
            '- Catalog categories and lifecycle states (draft, active, retired) map to TMF620 states.',
            '',
            '### TMF622 — Product Ordering',
            '- Order lifecycle states: acknowledged → inProgress → completed / failed / cancelled.',
            '- Order items carry action codes: add, modify, delete, noChange.',
            '- Expose order status via REST API aligned with TMF622 resource model.',
            '',
            '### TMF641 — Service Ordering',
            '- Service order states mirror TMF641: acknowledged, held, inProgress, completed, failed.',
            '- Service orders represent the fulfillment-side view of a product order.',
            '- Map orchestration step statuses to TMF641 lifecycle states for external system interop.',
            '',
            '## OmniScript / FlexCard Integration',
            '',
            '### Guided Selling',
            '- Use OmniScripts for guided product selection, configuration, and cart building.',
            '- FlexCards display product catalog summaries, comparison views, and order status.',
            '- Integration Procedures back OmniScript data operations — use DataRaptors for object I/O.',
            '- Never hardcode product IDs in OmniScripts — use DataRaptors to query catalog dynamically.',
            '',
            '### Service Qualification',
            '- Service qualification OmniScripts check network availability at the customer address.',
            '- Call external network inventory systems via Integration Procedures.',
            '- Cache qualification results to avoid repeated expensive lookups within the same session.',
            '- Display qualification results on FlexCards before allowing product selection.',
            '',
            '## Integration Patterns',
            '',
            '### BSS/OSS Integration',
            '- **BSS (Business Support Systems):** billing, CRM, revenue management.',
            '- **OSS (Operations Support Systems):** network provisioning, inventory, fault management.',
            '- Use Named Credentials for all external system authentication — never hardcode credentials.',
            '- Implement circuit breaker patterns for unreliable downstream systems.',
            '',
            '### Network Provisioning via Platform Events',
            '- Publish `OrderFulfillmentRequest__e` events for async network provisioning.',
            '- Include order item ID, action type (activate, modify, disconnect), and technical parameters.',
            '- Subscribe in downstream OSS systems or via Apex triggers for Salesforce-side processing.',
            '- Ensure event replay ID tracking for at-least-once delivery guarantees.',
            '',
            '### Billing System Sync',
            '- Sync customer accounts, subscriptions, and charges to external billing systems.',
            '- Use Change Data Capture or Platform Events for near-real-time billing updates.',
            '- Reconcile billing states periodically — handle discrepancies via scheduled batch jobs.',
            '- Never store payment card data in Salesforce — use tokenized references from the billing system.',
            '',
            '## Managed Package Safety (Vlocity Namespace: `vlocity_cmt__`)',
            '- **Do NOT add Apex triggers directly on Vlocity managed objects** (`vlocity_cmt__ProductOffering__c`, etc.).',
            '  Use Record-Triggered Flows or custom extension objects instead.',
            '- **Do NOT delete or rename Vlocity managed fields.** Extend only — add custom fields with a project prefix.',
            '- **Do NOT override Vlocity managed page layouts.** Clone them and assign to your Record Type.',
            '- Before each package upgrade, review Vlocity release notes for breaking changes.',
            '- Test in a sandbox with a full package upgrade before promoting to production.',
            '- Use `vlocity_cmt__` namespace prefix consistently when referencing managed objects in SOQL and Apex.',
            '',
            '## Security',
            '',
            '### Account Hierarchy Sharing for Enterprise Customers',
            '- Telecom enterprise customers often have complex account hierarchies (parent corp → subsidiaries → sites).',
            '- Use Account Hierarchy sharing rules to grant access across the hierarchy.',
            '- Configure role hierarchy or territory management to align with account ownership structure.',
            '- Validate that child account data (orders, billing) is visible to parent account owners.',
            '',
            '### Channel Partner Access',
            '- Partners (dealers, resellers) access the system via Experience Cloud portals.',
            '- Use Partner Community licenses with sharing sets scoped to the partner account hierarchy.',
            '- Restrict product catalog visibility by channel — not all offerings are available to all partners.',
            '- Audit partner access quarterly — remove inactive partner users promptly.',
            '',
            '## Testing',
            '',
            '### Test Factories for Product Catalog',
            '- Create a `CommTestDataFactory` class that builds:',
            '  - ProductOffering with linked ProductSpecification and attributes.',
            '  - Pricing elements (OTC, RC, usage) attached to the offering.',
            '  - Promotion records with eligibility criteria.',
            '- Reuse factory methods across all catalog-related test classes.',
            '- Never hardcode Vlocity record IDs in tests — query by name or unique external ID.',
            '',
            '### Test Factories for Order Decomposition',
            '- Build test orders with multiple line items spanning different product types.',
            '- Verify decomposition produces the expected number of fulfillment orders per domain.',
            '- Mock external system callouts in orchestration step tests using `Test.setMock()`.',
            '- Test fallout handling by simulating step failures and verifying retry/escalation behavior.',
            '- Assign Communications Cloud Permission Sets to test users in `@TestSetup`.',
            ...testCoverageStandards(),
            '',
            ...flsAndCrudEnforcement(),
            '',
            ...documentationStandards(),
            '',
            ...deployment(),
            '',
            ...semanticCommits(),
            '',
            ...generatedPromptsProtocol(),
            '',
            '## Communications Cloud References',
            '- Communications Cloud Developer Guide: https://developer.salesforce.com/docs/atlas.en-us.communications_cloud.meta/communications_cloud/',
            '- Industries CPQ Developer Guide: https://developer.salesforce.com/docs/atlas.en-us.industries_cpq.meta/industries_cpq/',
            '- Industries Order Management: https://developer.salesforce.com/docs/atlas.en-us.industries_order_management.meta/industries_order_management/',
            '- Vlocity/Industries Reference: https://help.salesforce.com/s/articleView?id=sf.comm_cloud_overview.htm',
            '',
            ...salesforceReferences(),
            ...getSharedSectionLines('communications'),
            '',
            ...interactionPreferences('Communications Cloud configuration'),
        ].join('\n');
    },
};
//# sourceMappingURL=communications.js.map