/*
 * 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 { generateDeveloperWorkflows } from '../generators/workflows/developer.js';
import { consultativeDesign, deployment, documentationStandards, fieldPermissionSetProtocol, flsAndCrudEnforcement, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, lucidDiagramStandards, salesforceReferences, semanticCommits, testCoverageStandards, } from './shared-sections.js';
export const developerProfile = {
    id: 'developer',
    label: 'Developer',
    ruleFile: 'developer-standards.mdc',
    extensions: [
        'salesforce.salesforcedx-vscode-apex-debugger',
        'salesforce.salesforcedx-vscode-apex-replay-debugger',
        'salesforce.sfdx-code-analyzer-vscode',
        'chuckjonas.apex-pmd',
        'chuckjonas.salesforce-diff',
        'omniphx.sfdx-auto-deployer',
        'hugoom.sfdx-autoheader',
        'vignaeshrama.sfdx-package-xml-generator',
        'financialforce.lana',
    ],
    capabilities: ['deploy', 'code-analysis', 'doc-sync', 'prompt-registry', 'declare-points', 'oclif-plugin'],
    cursorScope: 'auto-attach',
    globs: ['force-app/**/*.cls', 'force-app/**/*.trigger', 'force-app/**/lwc/**/*.js', 'force-app/**/lwc/**/*.html'],
    claudeAlwaysImport: true,
    workflows: generateDeveloperWorkflows,
    ruleContent() {
        return [
            '---',
            'description: Salesforce Developer Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# Salesforce Developer Standards',
            '',
            '> Role: Salesforce Developer — Salesforce Professional Services.',
            '',
            ...consultativeDesign(),
            '',
            '## Code Generation',
            '- Always read `sfdx-project.json` → `sourceApiVersion` before generating any Apex, LWC, or metadata.',
            '- Infer naming patterns from the existing project (prefixes, suffixes, casing). If no patterns exist, ask the user before creating new classes/components.',
            '- Common Salesforce patterns (when confirmed): Test classes `<ClassName>_Test`, Trigger handlers `<ObjectName>TriggerHandler`.',
            '',
            '## Apex Rules',
            '- Default: `with sharing` on all Apex classes.',
            '- Exception: Apex REST (`@RestResource`) classes → always `without sharing`.',
            '- **No SOQL or DML inside loops.** Collect, then query/DML once outside.',
            "- One trigger per object. Zero logic in triggers — delegate entirely to Kevin O'Hara Trigger Handler.",
            '- Scan for existing custom exception class before writing `try-catch`. If none exists, propose one.',
            '',
            '## Data Layer',
            '- Scan the project for an existing data access pattern. If none found, ask the user what strategy to use.',
            '- Always bulkify: handle 1 to N records.',
            '',
            '## LWC',
            '- Prioritize **SLDS Styling Hooks** over custom CSS.',
            '- Use **LDS 2** and **Lightning Data Service** whenever possible.',
            '- User feedback: Toasts with **Custom Labels**. Never hardcode strings.',
            '- **UX Gate (when generating LWC UI):** verify contrast (4.5:1), empty states, Cancel/Submit separation,',
            '  loading spinners, touch targets (44x44), and Custom Label usage. See `ux-standards.mdc` for full checklist.',
            '',
            '## Testing',
            '- **Deploy before testing (CRITICAL).** Never run a test class if the productive Apex class it covers',
            '  has not been deployed to the target sandbox yet. The sequence is always:',
            '  1. Deploy the modified productive class (`sf project deploy start`).',
            '  2. Wait for the deployment to succeed (monitor to completion).',
            '  3. Only then run the corresponding test class (`sf apex test run`).',
            '- If the user asks to run tests without deploying first, warn them and deploy before proceeding.',
            '- Wrap async Apex in `Test.startTest()` / `Test.stopTest()`.',
            ...testCoverageStandards(),
            '',
            '## Test Data Strategy',
            '- Use a centralized **TestDataFactory** class for all test data creation.',
            '- TestDataFactory must create records with all required fields populated — no partial inserts.',
            '- Map test users to **Permission Set Groups (PSGs)** — never assign Profiles directly in tests.',
            '- Use `System.runAs()` with PSG-based test users to validate field-level and object-level security.',
            '- For bulk tests: create N records (at minimum 200) to verify governor limit compliance.',
            '',
            '## LWC Unit Testing (Jest)',
            '- Co-locate tests in `__tests__/` next to the component: `myComponent/__tests__/myComponent.test.js`.',
            '- Use `@salesforce/lwc-jest` as the base. Run with `npm run test:unit` (or `jest`).',
            '- Mock all `@salesforce` imports in `jest.config.js`: labels, schema, custom permissions, and static resources.',
            '- Mock wire adapters using `@salesforce/wire-service-jest-util` or jest manual mocks.',
            '- Stub base Lightning components globally (`lwc`, `lightning/button`, etc.) in `jest.config.js` `moduleNameMapper`.',
            '- Test each LWC method and property in isolation. Do not test Salesforce platform behavior — test your logic.',
            '- Minimum coverage: every `@api` property, every `@wire` handler, and every user interaction (click, change) must have a test.',
            '',
            '## Async Apex',
            '- No fixed pattern. When async need arises, discuss architecture with the developer.',
            '- Evaluate `@future`, `Queueable`, `Batch`, and `Schedulable` based on governor limit context.',
            '',
            '## HTTP Callouts from Apex',
            '- **ALWAYS use Named Credentials** for all HTTP callouts — never hardcode endpoints, tokens, or credentials in Apex.',
            '- Define the Named Credential in Setup and reference it as `callout:NamedCredentialName/path`.',
            '- Use `HttpRequest`, `Http`, and `HttpResponse` classes. Check `response.getStatusCode()` before processing the body.',
            '- Wrap callouts in `try-catch`. Never assume a 200 — handle 4xx and 5xx explicitly.',
            '- Callouts are not allowed in Apex triggers. Move callout logic to `@future(callout=true)`, `Queueable`, or `Batch`.',
            '',
            ...flsAndCrudEnforcement(),
            '',
            ...fieldPermissionSetProtocol(),
            '',
            '## Error Handling',
            '- Scan for existing logging framework before writing `try-catch`.',
            '- Never use `eslint-disable` or `@SuppressWarnings` as a first resort.',
            '- Triggers: `addError()` with Custom Labels. LWC: Toast notifications.',
            '',
            '## Flow Awareness',
            '- Avoid Mega-Flows. Recommend Sub-flows for modularity.',
            '- One Record-Triggered Flow per object/context (Before Save / After Save).',
            '- Flow Orchestration: use ONLY for multi-step, multi-user, or long-running processes.',
            '',
            '## Platform Events & Change Data Capture',
            '- Use Platform Events for loosely-coupled, event-driven integrations between Apex, Flows, and external systems.',
            '- Always define a replay ID strategy: subscribe with `-1` (tip) for real-time, or store the last replay ID for durable subscribers.',
            '- Use `EventBus.publish()` for Apex-initiated events. Handle `Database.SaveResult` to detect publish failures.',
            '- For Change Data Capture: subscribe to `/data/ChangeEvents` or object-specific channels. Process `ChangeEventHeader` to detect operation type.',
            '- Never use Platform Events for synchronous request-response patterns — they are fire-and-forget.',
            '',
            '## Invocable Actions (Flow-Apex Bridge)',
            '- Use `@InvocableMethod` to expose Apex logic to Flow builders. Keep the method signature simple.',
            '- Mark input/output variables with `@InvocableVariable` and always include `label` and `description`.',
            '- One invocable method per class. Name the class descriptively: `InvocableCreateCase`, `InvocableAssignTerritory`.',
            '- Bulkify: the `@InvocableMethod` receives `List<Request>` — process all records, never just the first.',
            '- Return `List<Result>` with meaningful output fields that Flow builders can reference downstream.',
            '',
            '## MCP-First Development (Headless 360)',
            '- **Treat @salesforce/mcp tools as the primary integration surface** for AI agents and coding assistants.',
            '- The `@salesforce/mcp` package exposes 60+ tools: deploy, retrieve, run tests, SOQL, Code Analyzer, LWC, Aura→LWC migration, DevOps Center.',
            '- When building a new feature, ask: *"Can this be triggered by an AI agent via MCP without opening Salesforce UI?"* — if not, add an MCP-consumable API or action.',
            '- Use `--toolsets all` in MCP config to expose the full tool surface to coding assistants (already set in `a4d_mcp_settings.json` / `mcp.json`).',
            '- Expose custom business logic via **Invocable Actions** or **Apex REST** so agents can invoke it through the platform MCP layer.',
            '- Document any new MCP-accessible capability in `/docs/mcp-surface.md`: tool name, inputs, outputs, permissions required.',
            '',
            '## React for Salesforce (Beta — Multi-Framework)',
            '- **Multi-Framework support announced at TDX 2026 (open beta).** React components can now run natively inside Salesforce.',
            '- **Currently only available in scratch orgs and sandboxes** — do NOT use in production until GA.',
            '- Use React when: building highly interactive UIs that are difficult in LWC (complex state, rich animations, reusing existing React component libraries).',
            '- Use LWC when: building standard Salesforce record pages, forms, and admin tools — LWC remains the default.',
            '- React components in Salesforce still use **LDS (Lightning Data Service)** for data access — do not bypass the platform data layer.',
            '- Apply **SLDS 2 styling hooks** (`--slds-g-*`) to React components the same way as LWC — no custom hex colors.',
            '- Track GA announcement before recommending React for any production implementation.',
            '',
            '## Apex Recipes Pattern',
            '- **Apex Recipes** are self-contained, runnable Apex classes that demonstrate a single platform capability — use them as a reference library, not as production service classes.',
            '- When a requirement matches an Apex Recipe pattern (e.g., callout, batch, platform event), read the recipe first to understand the platform idiom before writing custom code.',
            '- **Do NOT deploy Apex Recipes as-is to production.** Extract the relevant pattern into a properly named service class following project conventions.',
            '- If a recipe demonstrates a pattern already implemented in the project, prefer the existing project implementation over the recipe pattern.',
            '- Use recipes for: onboarding new developers to platform capabilities, evaluating governor limit behavior before implementing, and quick PoC validation.',
            '',
            '## Custom Metadata Types',
            '- Use **CMDT** for app configuration that must be deployable (e.g., mapping tables, feature flags, thresholds).',
            '- Use **Custom Settings** only for org-level or user-level runtime toggles that change without deployment.',
            '- Use **Custom Labels** for translatable user-facing text, NOT for configuration values.',
            '- CMDT API Names: `<Feature>_Config__mdt`. Records: descriptive `DeveloperName`.',
            '- Always seed CMDT records in the deployment package — never rely on manual creation in target orgs.',
            '',
            ...generatedPromptsProtocol(),
            '',
            ...documentationStandards(),
            '',
            ...deployment(),
            '',
            ...semanticCommits(),
            '',
            '## Sub-agent Handover',
            '- Pass to sub-agents: API version from `sfdx-project.json`, existing trigger handler pattern,',
            '  data layer strategy, naming conventions, and test user PSG names.',
            '- Sub-agents must follow: one Assert per test, zero logic in triggers.',
            '',
            ...lucidDiagramStandards(),
            '',
            ...salesforceReferences(),
            ...getSharedSectionLines('developer'),
            '',
            ...interactionPreferences(),
        ].join('\n');
    },
};
//# sourceMappingURL=developer.js.map