/*
 * 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 } from 'node:fs';
import { join } from 'node:path';
import { generateManufacturingWorkflows } from '../generators/workflows/manufacturing.js';
import { consultativeDesign, deployment, documentationStandards, flsAndCrudEnforcement, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, nativeConfigurationFirst, salesforceReferences, semanticCommits, testCoverageStandards, } from './shared-sections.js';
export const manufacturingProfile = {
    id: 'manufacturing',
    label: 'Manufacturing Cloud',
    ruleFile: 'manufacturing-standards.mdc',
    extensions: ['salesforce.salesforcedx-vscode'],
    capabilities: ['deploy', 'code-analysis', 'prompt-registry', 'declare-points'],
    cursorScope: 'description',
    detect(cwd) {
        return (existsSync(join(cwd, 'force-app/main/default/objects/ManufacturingForecast')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/AccountForecast')) ||
            existsSync(join(cwd, 'force-app/main/default/customMetadata/MfgProgramRebateType')));
    },
    workflows: generateManufacturingWorkflows,
    ruleContent() {
        return [
            '---',
            'description: Manufacturing Cloud Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# Manufacturing Cloud Standards',
            '',
            '> Role: Manufacturing Cloud Developer / Consultant — Salesforce Professional Services.',
            '> Manufacturing Cloud is a managed package on top of core Salesforce. All standards here apply **in addition to** general Apex and LWC rules.',
            '',
            ...consultativeDesign('Manufacturing Cloud data model and configuration decisions'),
            '',
            ...nativeConfigurationFirst(),
            '',
            '## Manufacturing Cloud Data Model (CRITICAL)',
            '- **Sales Agreements** are the foundation for tracking committed volumes and revenue between manufacturer and customer.',
            '  Each agreement links to an Account and contains product-level line items with planned quantities.',
            '- **Account-Based Forecasting** provides collaborative demand planning with adjustment capabilities.',
            '  Forecasts roll up from product-level to account-level with configurable time periods.',
            '- **Manufacturing Programs** manage rebate definitions, incentive tiers, and payout schedules.',
            '- **Never create custom objects that duplicate native Manufacturing Cloud functionality.**',
            '  The managed package data model is the system of record for agreements, forecasts, and rebates.',
            '',
            '### Core Manufacturing Cloud Objects',
            '| Object | API Name | Purpose |',
            '|--------|----------|---------|',
            '| Sales Agreement | `SalesAgreement` | Header for customer volume/revenue commitments |',
            '| Sales Agreement Product | `SalesAgreementProduct` | Product-level line items with planned vs. actual quantities |',
            '| Account Forecast | `AccountForecast` | Demand forecast at account level with time-period granularity |',
            '| Account Forecast Adjustment | `AccountForecastAdjustment` | Collaborative adjustments with audit trail |',
            '| Manufacturing Program | `MfgProgram` | Rebate/incentive program container |',
            '| Manufacturing Program Rebate Type | `MfgProgramRebateType` | Rebate calculation rules and tier definitions |',
            '',
            '### Sales Agreement Model',
            '- `SalesAgreement` → parent header with Account, date range, and status lifecycle.',
            '- `SalesAgreementProduct` → child line items per Product2 with:',
            '  - `PlannedQuantity` — committed volume for the agreement period.',
            '  - `ActualQuantity` — fulfilled volume (calculated from Orders or custom logic).',
            '  - Schedule fields for time-based quantity breakdowns.',
            '- Actuals calculation: configure in Manufacturing Cloud Setup (Order-based or custom Apex interface).',
            '- Status lifecycle: Draft → Activated → InReview → Expired.',
            '',
            '### Account-Based Forecasting Framework',
            '- **Forecast Sets:** group accounts into forecast cohorts by region, product family, or segment.',
            '- **Forecast Periods:** configurable granularity (monthly, quarterly, annual).',
            '- **Adjustments:** `AccountForecastAdjustment` records allow sales reps and managers to modify',
            '  forecast values with reason codes and approval workflows.',
            '- **Sharing:** forecast visibility controlled by OWD + sharing rules on `AccountForecast`.',
            '  Use sharing sets for partner/distributor access to their own forecast data.',
            '- **Baseline sources:** seed forecasts from Sales Agreement planned quantities, historical orders,',
            '  or external demand signals via integration.',
            '',
            '### Rebate Management',
            '- **Program Types:** Volume-based tiers, flat percentage, growth incentive, mix incentive, loyalty.',
            '- **Calculation:** `MfgProgramRebateType` defines the formula — percentage, tier breakpoints, or custom.',
            '- **Payouts:** periodic calculation of earned rebates against qualified actuals.',
            '  Status lifecycle: Pending Calculation → Calculated → Approved → Paid.',
            '- **Accruals:** estimated rebate liability posted at period close; reversed on actual payout.',
            '- **Integration:** payout data typically syncs to ERP/GL via Platform Events or MuleSoft.',
            '',
            '## Integration Patterns',
            '- **ERP Integration (Order Sync):**',
            '  - Inbound: ERP order fulfillment data feeds `SalesAgreementProduct` actuals.',
            '  - Use MuleSoft or Platform Events (`OrderFulfillmentEvent__e`) for near-real-time sync.',
            '  - Batch: nightly batch job via Schedulable Apex for high-volume order imports.',
            '- **Demand Signal Integration:**',
            '  - External demand forecasts (POS data, distributor sell-through) feed `AccountForecast` baselines.',
            '  - Use Data Cloud or MuleSoft ETL to ingest and transform external signals.',
            '- **Finance/GL Integration (Rebate Payouts):**',
            '  - Publish `RebatePayoutEvent__e` Platform Events on payout approval.',
            '  - MuleSoft subscriber routes payout records to the ERP Accounts Payable module.',
            '  - Include: Program ID, Account, Amount, Period, Currency, GL Account Code.',
            '- **Named Credentials:** always use Named Credentials for external system authentication.',
            '  Never store ERP credentials in custom settings or Apex constants.',
            '',
            '## Managed Package Safety Rules',
            '- **Do NOT add Apex triggers directly on Manufacturing Cloud managed objects** (`SalesAgreement`, `SalesAgreementProduct`, `MfgProgram`, etc.).',
            '  Use Record-Triggered Flows or a custom extension object instead.',
            '- **Do NOT delete or rename managed fields.** Extend only — add custom fields with a project prefix.',
            '- **Do NOT override managed page layouts.** Clone them and assign the clone to your Record Type.',
            '- Before each package upgrade, run `sf package version list --package <MFG_PACKAGE_ID>` and review the release notes for breaking changes.',
            '- Test in a sandbox with a full package upgrade before promoting to production.',
            '',
            '## Security & Sharing',
            '- **OWD for Forecast Data:** set `AccountForecast` OWD to Private when forecast data is sensitive',
            '  (competitive pricing, volume commitments). Grant access via sharing rules by role or territory.',
            '- **Partner Access:** use Sharing Sets on `AccountForecast` and `SalesAgreement` to grant',
            '  partner community users visibility into their own agreement and forecast records only.',
            '- **Sales Agreement Security:** agreements often contain pricing terms — restrict access',
            '  to agreement owners and their management chain via Account Team or role hierarchy.',
            '- **Rebate Program Visibility:** limit `MfgProgram` access to finance and sales ops teams.',
            '  Use Permission Sets to control who can approve payouts vs. view-only access.',
            '- **Manufacturing Cloud Permission Sets to assign (do not create duplicates):**',
            '  - `ManufacturingCloud` — base Manufacturing Cloud access',
            '  - `ManufacturingCloudForecasting` — Account-Based Forecasting features',
            '  - `ManufacturingCloudRebates` — Rebate Management features',
            '',
            '## Testing Manufacturing Cloud',
            '- **Use TestDataFactory** to create Sales Agreements, Agreement Products, and Forecast records in test setup.',
            '  Sales Agreement creation requires an active Account and valid Product2 records.',
            '- **Test factory pattern for SalesAgreement:**',
            '  1. Create Account (customer).',
            '  2. Create Product2 + PricebookEntry.',
            '  3. Insert `SalesAgreement` with Account, StartDate, EndDate, Status = "Draft".',
            '  4. Insert `SalesAgreementProduct` linking to the agreement and product.',
            '  5. Activate the agreement (Status = "Activated") to trigger actuals calculation.',
            '- **Test factory pattern for AccountForecast:**',
            '  1. Create Account + Forecast Set configuration.',
            '  2. Insert `AccountForecast` with Account, ForecastSet, Period, and baseline values.',
            '  3. Insert `AccountForecastAdjustment` to test adjustment workflows.',
            '- Assign Manufacturing Cloud Permission Sets to test users in `@TestSetup`.',
            '- Mock ERP integration callouts using `Test.setMock(HttpCalloutMock.class, ...)` pattern.',
            ...testCoverageStandards(),
            '',
            ...flsAndCrudEnforcement(),
            '',
            ...documentationStandards(),
            '',
            ...deployment(),
            '',
            ...semanticCommits(),
            '',
            ...generatedPromptsProtocol(),
            '',
            '## Manufacturing Cloud References',
            '- Manufacturing Cloud Developer Guide: https://developer.salesforce.com/docs/atlas.en-us.manufacturing_cloud.meta/manufacturing_cloud/',
            '- Manufacturing Cloud Object Reference: https://developer.salesforce.com/docs/atlas.en-us.manufacturing_cloud_object_reference.meta/manufacturing_cloud_object_reference/',
            '- Rebate Management Guide: https://help.salesforce.com/s/articleView?id=sf.mfg_rebate_management.htm',
            '',
            ...salesforceReferences(),
            ...getSharedSectionLines('manufacturing'),
            '',
            ...interactionPreferences('Manufacturing Cloud configuration'),
        ].join('\n');
    },
};
//# sourceMappingURL=manufacturing.js.map