/*
 * 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 { generateFscWorkflows } from '../generators/workflows/fsc.js';
import { consultativeDesign, deployment, documentationStandards, flsAndCrudEnforcement, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, nativeConfigurationFirst, salesforceReferences, semanticCommits, testCoverageStandards, } from './shared-sections.js';
export const fscProfile = {
    id: 'fsc',
    label: 'Financial Services Cloud',
    ruleFile: 'fsc-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/FinServ__FinancialAccount__c')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/FinServ__Referral__c')) ||
            existsSync(join(cwd, 'force-app/main/default/customMetadata/FinServ__RollupByLookupConfig__mdt')));
    },
    workflows: generateFscWorkflows,
    ruleContent() {
        return [
            '---',
            'description: Financial Services Cloud (FSC) Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# Financial Services Cloud (FSC) Standards',
            '',
            '> Role: FSC Developer / Consultant — Salesforce Professional Services.',
            '> FSC is a managed package on top of core Salesforce. All standards here apply **in addition to** general Apex and LWC rules.',
            '',
            ...consultativeDesign('FSC data model and configuration decisions'),
            '',
            ...nativeConfigurationFirst(),
            '',
            '## FSC Data Model (CRITICAL)',
            '- **PersonAccount for individuals.** Enable PersonAccount in Setup → Account Settings.',
            '  Use a dedicated Record Type (e.g., `Individual_Client`) — never share a Record Type between PersonAccount and Business Account.',
            '- **Household Account** uses Record Type `IndustriesHousehold`. Link members via `FinServ__ContactContactRelation__c`.',
            '  Set `FinServ__PrimaryGroup__c` on Contact → Household Account. One Contact may belong to multiple groups but only one primary.',
            '- **Never create a custom "household" object.** The FSC household model is the system of record for group relationships.',
            '',
            '### Core FSC Objects',
            '| Object | API Name | Purpose |',
            '|--------|----------|---------|',
            '| Financial Account | `FinServ__FinancialAccount__c` | Client financial products (bank, investment, insurance, loan) |',
            '| Financial Account Role | `FinServ__FinancialAccountRole__c` | Ownership roles: Primary Owner, Joint Owner, Beneficiary, PoA |',
            '| Financial Account Transaction | `FinServ__FinancialAccountTransaction__c` | Transaction history linked to a Financial Account |',
            '| Assets & Liabilities | `FinServ__AssetsAndLiabilities__c` | Non-product assets/liabilities for net worth calculation |',
            '| Financial Goal | `FinServ__FinancialGoal__c` | Client goals: Retirement, Education, Emergency Fund |',
            '| Referral | `FinServ__Referral__c` | Internal/external referral tracking with lifecycle stages |',
            '| Contact Contact Relation | `FinServ__ContactContactRelation__c` | Reciprocal role relationships between Contacts |',
            '| Lead (FSC extension) | `Lead` with FSC fields | Use standard Lead + FSC fields; do NOT create a custom lead object |',
            '',
            '### Financial Account Record Types',
            '- `BankAccount` — Checking / Savings',
            '- `InvestmentAccount` — Brokerage / Portfolio',
            '- `InsurancePolicy` — Life, Auto, Property',
            '- `CreditFacility` — Mortgage, Loan, Line of Credit',
            '- Match business product types to these Record Types before proposing custom objects.',
            '',
            '## Managed Package Safety Rules',
            '- **Do NOT add Apex triggers directly on FSC managed objects** (`FinServ__FinancialAccount__c`, `FinServ__Referral__c`, etc.).',
            '  Use Record-Triggered Flows or a custom junction/extension object instead.',
            '- **Do NOT delete or rename FSC managed fields.** Extend only — add custom fields with a project prefix.',
            '- **Do NOT override FSC managed page layouts.** Clone them and assign the clone to your Record Type.',
            '- Before each package upgrade, run `sf package version list --package <FSC_PACKAGE_ID>` and review the release notes for breaking changes.',
            '- Test in a sandbox with a full package upgrade before promoting to production.',
            '',
            '## Rollup Framework (FinServ__RollupByLookupConfig__mdt)',
            '- FSC provides a rollup framework via Custom Metadata Type `FinServ__RollupByLookupConfig__mdt`.',
            '  Use it for aggregating Financial Account values (balance, count) to Household or Contact.',
            '- **Never build custom Apex rollup triggers on FSC objects** — they conflict with the managed rollup engine.',
            '- Configuration fields:',
            '  - `FinServ__SourceObject__c` — object being summarized (e.g., `FinServ__FinancialAccount__c`)',
            '  - `FinServ__SourceField__c` — numeric field to aggregate (e.g., `FinServ__Balance__c`)',
            '  - `FinServ__TargetObject__c` — parent object receiving the rollup (e.g., `Account`)',
            '  - `FinServ__TargetField__c` — field on the parent receiving the result',
            '  - `FinServ__LookupField__c` — relationship field (e.g., `FinServ__PrimaryGroup__c`)',
            '  - `FinServ__Operation__c` — SUM, COUNT, MIN, MAX, AVERAGE',
            '- Deploy `customMetadata/FinServ__RollupByLookupConfig__mdt/` with the rest of your metadata package.',
            '',
            '## Actionable Relationship Center (ARC)',
            '- ARC is the current FSC relationship visualization — it replaced the legacy Relationship Viewer.',
            '- Configure in Setup → Financial Services → Actionable Relationship Center.',
            '- Key concepts: Cards (nodes per object/record type), Groups (relationship sets), Display Categories (panel sections).',
            '- Assign ARC config to Lightning pages via the **Actionable Relationship Center** standard component.',
            '- Use **Reciprocal Roles** (Setup → Financial Services → Reciprocal Roles) to define bidirectional labels',
            '  (e.g., Spouse ↔ Spouse, Parent ↔ Child). Instantiate via `FinServ__ContactContactRelation__c` records.',
            '- Add card actions sparingly — each action should map to a specific Flow or quick action, not generic navigation.',
            '- Test ARC with restricted profiles: Display Category visibility is not automatic — validate per role.',
            '',
            '## Sharing & Security',
            '- FSC uses **Account Team** sharing for advisor-level access to client records.',
            '  Add advisors to the Account Team with appropriate Team Member Role and Account access level.',
            '- **Advisor hierarchy sharing:** configure sharing rules or Apex managed sharing for org-wide defaults below Private.',
            '- `FinServ__FinancialAccount__c` inherits sharing from the parent Account — do NOT set OWD to Public on Financial Accounts.',
            '- For compliance use cases: use **Restriction Rules** (Setup → Security → Restriction Rules) to limit record visibility',
            '  by segment or regulatory region without custom Apex sharing.',
            '- FSC Permission Sets to assign (do not create duplicates):',
            '  - `FinancialServicesCloud` — base FSC access',
            '  - `FinancialServicesCloudExtension` — advanced features (ARC, Goals, Referrals)',
            '  - `FSCInsurance` / `FSCMortgage` / `FSCWealth` — industry-specific feature sets',
            '',
            '## Referral Management',
            '- Use `FinServ__Referral__c` for all referral tracking — internal advisor-to-advisor and external client referrals.',
            '- Key fields: `FinServ__ReferredBy__c` (User), `FinServ__ReferredTo__c` (User), `FinServ__Account__c` (Account),',
            '  `FinServ__Status__c` (picklist), `FinServ__ConvertedOpportunity__c` (Opportunity).',
            '- Automate lifecycle via Record-Triggered Flow (not triggers on the managed object).',
            '- On conversion: populate `FinServ__ConvertedOpportunity__c` and log a completed Activity.',
            '',
            '## Financial Goals',
            '- Use `FinServ__FinancialGoal__c` for client planning goals (Retirement, Education, Emergency Fund).',
            '- Key fields: `FinServ__ActualValue__c`, `FinServ__TargetValue__c`, `FinServ__TargetDate__c`, `FinServ__GoalType__c`.',
            '- Track progress via the `FinServ__Progress__c` formula or a custom Apex scheduled job that updates it nightly.',
            '- Display goals on the client 360 page using the **Financial Goals** standard FSC component.',
            '',
            '## Einstein Next Best Action for FSC',
            '- Use Einstein Next Best Action (NBA) to surface referral and product recommendations on advisor pages.',
            '- Define Recommendation Strategies using Flow to evaluate client attributes (AUM, product gaps, life events).',
            '- Populate the **Einstein Next Best Action** component on the Account/Contact Lightning page.',
            '- For advanced scoring: connect Data Cloud Unified Profiles to feed real-time propensity scores into NBA strategies.',
            '- Gate all NBA-triggered actions behind human confirmation — never auto-execute DML from a recommendation.',
            '',
            '## CRM Analytics (Tableau CRM) for FSC',
            '- FSC ships with pre-built CRM Analytics apps: **FSC Analytics**, **Advisor Analytics**, **Insurance Analytics**.',
            '- Before building custom lenses, explore whether the default apps cover the requirement.',
            '- Data sync: FSC objects sync to CRM Analytics via the standard connector — add `FinServ__FinancialAccount__c`,',
            '  `FinServ__FinancialGoal__c`, and `FinServ__Referral__c` to the dataflow.',
            '- Use **Interaction Studio** (now Marketing Cloud Personalization) for behavioral data — not CRM Analytics.',
            '',
            '## Industry-Specific Overlays',
            '### Wealth Management',
            '- Use `InvestmentAccount` Record Type. Key fields: `FinServ__AUM__c`, `FinServ__PortfolioStrategy__c`.',
            '- Model advisor books of business via Account Team or custom junction object.',
            '',
            '### Retail Banking',
            '- Use `BankAccount` Record Type. `FinServ__Balance__c` drives household rollups.',
            '- Integrate core banking via MuleSoft or Named Credential callouts — never embed account numbers in Apex.',
            '',
            '### Insurance',
            '- Use `InsurancePolicy` Record Type. Enable FSCInsurance permission set.',
            '- Key objects: `InsurancePolicy`, `InsurancePolicyParticipant`, `InsurancePolicyCoverage`, `Claim`, `ClaimParticipant`.',
            '- Integrate with policy administration systems via Platform Events or Apex callouts.',
            '',
            '### Mortgage / Lending',
            '- Use `CreditFacility` Record Type. Track loan applications via standard `Opportunity` with FSC fields.',
            '- Enable FSCMortgage permission set for the Mortgage loan origination UI components.',
            '',
            '## Data Quality & Deduplication',
            '- Enable **Duplicate Management** for Account and Contact — FSC clients generate duplicates via advisor imports.',
            '- Define Matching Rules based on Tax ID, email, or name + DOB for PersonAccounts.',
            '- Run `Duplicate Jobs` (Setup → Duplicate Jobs) periodically on the full org to surface merge candidates.',
            '- Never merge PersonAccounts with Business Accounts — the merge engine does not handle mixed account models.',
            '',
            '## Testing FSC',
            '- **Use TestDataFactory** to create PersonAccounts, Household Accounts, and Financial Accounts in test setup.',
            '  PersonAccount creation requires inserting an Account with a PersonAccount Record Type Id.',
            '- FSC rollup triggers fire in test context — always query the target rollup field after the insert in the same transaction.',
            '- Assign FSC Permission Sets to test users in `@TestSetup` — `FinancialServicesCloud` is required for FSC object access.',
            '- Mock managed package callouts where present using `Test.setMock(HttpCalloutMock.class, ...)` pattern.',
            ...testCoverageStandards(),
            '',
            ...flsAndCrudEnforcement(),
            '',
            ...documentationStandards(),
            '',
            ...deployment(),
            '',
            ...semanticCommits(),
            '',
            ...generatedPromptsProtocol(),
            '',
            '## FSC References',
            '- Financial Services Cloud Developer Guide: https://developer.salesforce.com/docs/atlas.en-us.financial_services_cloud_developer_guide.meta/financial_services_cloud_developer_guide/',
            '- FSC Object Reference: https://developer.salesforce.com/docs/atlas.en-us.financial_services_cloud_object_reference.meta/financial_services_cloud_object_reference/',
            '- Rollup By Lookup Configuration: https://help.salesforce.com/s/articleView?id=sf.fsc_rollup_by_lookup.htm',
            '- ARC Setup Guide: https://help.salesforce.com/s/articleView?id=sf.fsc_arc_setup.htm',
            '- FSC Release Notes: https://help.salesforce.com/s/articleView?id=release-notes.rn_fsc.htm',
            '',
            ...salesforceReferences(),
            ...getSharedSectionLines('fsc'),
            '',
            ...interactionPreferences('FSC configuration'),
        ].join('\n');
    },
};
//# sourceMappingURL=fsc.js.map