/*
 * 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 { generateAutomotiveWorkflows } from '../generators/workflows/automotive.js';
import { consultativeDesign, deployment, documentationStandards, flsAndCrudEnforcement, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, nativeConfigurationFirst, salesforceReferences, semanticCommits, testCoverageStandards, } from './shared-sections.js';
export const automotiveProfile = {
    id: 'automotive',
    label: 'Automotive Cloud',
    ruleFile: 'automotive-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/Vehicle__c')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/VehicleDefinition__c')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/DealerPerformance')));
    },
    workflows: generateAutomotiveWorkflows,
    ruleContent() {
        return [
            '---',
            'description: Automotive Cloud Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# Automotive Cloud Standards',
            '',
            '> Role: Automotive Cloud Developer / Consultant — Salesforce Professional Services.',
            '> Automotive Cloud is an industry solution on top of core Salesforce. All standards here apply **in addition to** general Apex and LWC rules.',
            '',
            ...consultativeDesign('Automotive Cloud data model and configuration decisions'),
            '',
            ...nativeConfigurationFirst(),
            '',
            '## Automotive Cloud Data Model (CRITICAL)',
            '',
            '### Vehicle Lifecycle',
            'The Automotive Cloud data model tracks vehicles through their complete lifecycle:',
            '```',
            'VehicleDefinition (catalog) → Vehicle (physical unit) → Sale → Service → Trade-In',
            '```',
            '',
            '### Core Automotive Objects',
            '| Object | API Name | Purpose |',
            '|--------|----------|---------|',
            '| Vehicle Definition | `VehicleDefinition__c` | Product catalog entry: Make, Model, Year, Trim, Engine, MSRP |',
            '| Vehicle | `Vehicle__c` | Physical unit identified by VIN — inventory, ownership, status |',
            '| Vehicle Asset | `VehicleAsset` | Post-sale asset record linking vehicle to owner Account |',
            '| Test Drive | `TestDrive` | Scheduled and completed test drive records |',
            '| Trade-In | `TradeIn` | Trade-in valuation linked to an Opportunity |',
            '| Dealer Performance | `DealerPerformance` | Dealer KPI tracking: units sold, gross profit, CSI |',
            '',
            '### Vehicle Definition (Catalog)',
            '- Represents an abstract product definition — NOT a physical vehicle.',
            '- Key fields: Make, Model, Year, Trim, Engine Type, Transmission, MSRP, Segment.',
            '- Use Record Types by segment (Sedan, SUV, Truck, EV) if page layouts differ.',
            '- One VehicleDefinition can have many Vehicle records (one-to-many).',
            '',
            '### Vehicle (Physical Unit)',
            '- Each record represents a single physical vehicle identified by a unique VIN.',
            '- Key fields: VIN (17 chars, unique), Vehicle Definition (lookup), Status, Stock Number, Colors, Dealer, List Price.',
            '- **VIN validation:** 17 alphanumeric characters excluding I, O, Q. Compute check digit at position 9.',
            '- Status picklist lifecycle: `In Transit → In Stock → Reserved → Sold → Delivered`.',
            '- Used vehicles re-enter inventory via Trade-In with status reset to "In Stock".',
            '',
            '### Test Drive',
            '- Links a Contact (prospect) to a Vehicle for a scheduled test drive.',
            '- Key fields: Contact, Vehicle, Scheduled Date/Time, Status (Scheduled, Completed, Cancelled, No-Show), Notes.',
            '- Use Record-Triggered Flows to create follow-up Tasks after completed test drives.',
            '',
            '### Trade-In',
            '- Captures vehicle valuation during a sale negotiation.',
            '- Key fields: Vehicle (the trade-in unit), Opportunity (the new sale), Estimated Value, Appraised Value, Condition.',
            '- On Opportunity close: update trade-in Vehicle status and optionally create a new inventory Vehicle record.',
            '',
            '## Dealer Management',
            '',
            '### Dealer Account Model',
            '- Dealers are Account records with a dedicated `Dealer` Record Type.',
            '- Key fields: Dealer Code (external ID for DMS integration), Brand Affiliation, Territory, Dealer Tier.',
            '- Multi-rooftop dealers: use Account hierarchy (parent = dealer group, children = locations).',
            '',
            '### Performance Tracking',
            '- `DealerPerformance` records track KPIs per dealer per period.',
            '- Metrics: Units Sold (New/Used), Gross Profit, CSI Score, Service Revenue, Parts Revenue.',
            '- Automate tier calculation via Record-Triggered Flow on DealerPerformance insert/update.',
            '- Generate monthly scorecards via Scheduled Flow or Apex Batch.',
            '',
            '### Territory Assignment',
            '- Use Enterprise Territory Management (Territory2) for complex, overlapping territory rules.',
            '- For simpler models: custom `Territory__c` object with lookup on dealer Account.',
            '- Sharing rules must align with territory model — dealers see only their territory data.',
            '',
            '### Incentive Programs',
            '- Model incentive programs with: Name, Type (Volume/Stair-Step/CSI-Based), Thresholds, Rewards, Eligible Tiers.',
            '- Evaluate eligibility at period end via Scheduled Apex or Flow.',
            '- Surface payouts on dealer Account page via related list.',
            '',
            '## Lead Management (Automotive-Specific)',
            '',
            '### Lead Scoring',
            '- Extend standard Lead with automotive fields: Vehicle Interest (lookup to VehicleDefinition), Purchase Timeline, Trade-In Intent.',
            '- Score leads based on: engagement recency, test drive completion, trade-in submission, finance pre-approval.',
            '- Use Einstein Lead Scoring or a custom scoring Flow to prioritize dealer follow-up.',
            '',
            '### Test Drive Scheduling',
            '- Integrate test drive scheduling into the lead nurture flow.',
            '- On Lead conversion: carry forward test drive history and vehicle interest to the new Opportunity.',
            '- Automate reminder notifications to both prospect and dealer before scheduled test drives.',
            '',
            '### Trade-In Valuations',
            '- Allow prospects to submit trade-in details during the lead stage.',
            '- Integrate with third-party valuation APIs (KBB, Black Book) via Named Credentials.',
            '- Store valuations on the Trade-In object linked to the Lead or Opportunity.',
            '',
            '## Integration Patterns',
            '',
            '### DMS (Dealer Management System) Integration',
            '- Connect to DMS (CDK, Reynolds & Reynolds, Dealertrack) via REST APIs and Named Credentials.',
            '- Sync patterns:',
            '  - **Inventory sync (inbound):** OEM/DMS pushes vehicle data → Platform Events → Apex subscriber creates/updates Vehicle records.',
            '  - **Sale sync (outbound):** On Opportunity close → callout to DMS to register the sale.',
            '  - **Performance sync (inbound):** Nightly batch pulls dealer KPIs from DMS into DealerPerformance records.',
            '- Use Platform Events for real-time inventory updates; Apex Batch for bulk historical sync.',
            '',
            '### OEM Inventory Sync',
            '- OEM feeds typically arrive as flat files (CSV/XML) or API payloads.',
            '- Ingest via Salesforce Data Loader (scheduled), MuleSoft, or custom Apex Batch.',
            '- Map OEM vehicle codes to VehicleDefinition records using a Custom Metadata mapping table.',
            '- Upsert Vehicle records by VIN to avoid duplicates.',
            '',
            '### Named Credential Best Practices',
            '- One Named Credential per external system (DMS, valuation API, OEM portal).',
            '- Never hardcode API keys or credentials in Apex — always use Named Credentials or Custom Metadata.',
            '- Use External Credentials (API v58+) for OAuth 2.0 client credentials flow.',
            '',
            '## Managed Package Safety Rules',
            '- **Do NOT add Apex triggers directly on Automotive Cloud managed objects.**',
            '  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, review release notes for breaking changes.',
            '- Test in a sandbox with a full package upgrade before promoting to production.',
            '',
            '## Sharing & Security',
            '',
            '### Dealer-Level Sharing',
            '- Set OWD for Vehicle to Private or Public Read Only depending on multi-dealer visibility requirements.',
            '- Use Sharing Rules or Apex Managed Sharing to grant dealer-specific access to their inventory.',
            '- Dealer users should only see vehicles assigned to their dealership Account.',
            '',
            '### Territory-Based Access',
            '- Align record access with territory assignments.',
            '- Use Territory2 sharing rules or custom sharing rules keyed on the Territory field.',
            '- Regional managers see all dealers in their territory; district managers see their district only.',
            '',
            '### OWD Recommendations',
            '| Object | Recommended OWD | Rationale |',
            '|--------|----------------|-----------|',
            '| Vehicle | Private | Dealers see only their inventory |',
            '| VehicleDefinition | Public Read Only | Catalog is shared across all dealers |',
            '| DealerPerformance | Private | Sensitive KPI data per dealer |',
            '| TestDrive | Controlled by Parent (Account) | Inherits from dealer Account sharing |',
            '| TradeIn | Controlled by Parent (Opportunity) | Inherits from Opportunity sharing |',
            '',
            '### Permission Sets',
            '- Create dedicated Permission Sets for Automotive Cloud access:',
            '  - `AutomotiveCloud_Base` — read access to Vehicle, VehicleDefinition, TestDrive',
            '  - `AutomotiveCloud_DealerManager` — full CRUD on DealerPerformance, Incentives',
            '  - `AutomotiveCloud_Inventory` — create/edit Vehicle records, manage stock',
            '- Assign via Permission Set Groups per dealer role.',
            '',
            '## Testing Automotive Cloud',
            '',
            '### Test Data Factory Pattern',
            '- Create a `TestDataFactory` class with methods for generating Automotive test data.',
            '- **VIN generation:** Use a utility method that produces valid 17-character VINs with correct check digit.',
            '  ```apex',
            '  public static String generateVIN() {',
            '      // Generate valid VIN with check digit at position 9',
            "      String base = '1HGCM82633A' + String.valueOf(Math.round(Math.random() * 99999)).leftPad(5, '0');",
            '      return base.left(9) + computeCheckDigit(base) + base.substring(10);',
            '  }',
            '  ```',
            '- **Vehicle Definition factory:** Create catalog entries with Make/Model/Year/Trim.',
            '- **Vehicle factory:** Create inventory records linked to a VehicleDefinition with valid VIN.',
            '- **Dealer factory:** Create dealer Accounts with Dealer Code and Territory assignment.',
            '',
            '### Test Patterns',
            '- Use `@TestSetup` for shared vehicle catalog and dealer data.',
            '- Test VIN uniqueness enforcement with duplicate insert assertions.',
            '- Test status transitions: verify Flow/trigger updates Vehicle status on Opportunity stage changes.',
            '- Test sharing: use `System.runAs()` with dealer users to verify record visibility boundaries.',
            '- Mock DMS callouts with `Test.setMock(HttpCalloutMock.class, ...)` for integration tests.',
            ...testCoverageStandards(),
            '',
            ...flsAndCrudEnforcement(),
            '',
            ...documentationStandards(),
            '',
            ...deployment(),
            '',
            ...semanticCommits(),
            '',
            ...generatedPromptsProtocol(),
            '',
            '## Automotive Cloud References',
            '- Automotive Cloud Developer Guide: https://developer.salesforce.com/docs/atlas.en-us.automotive_cloud.meta/automotive_cloud/',
            '- Automotive Cloud Object Reference: https://developer.salesforce.com/docs/atlas.en-us.automotive_cloud_object_reference.meta/automotive_cloud_object_reference/',
            '- Dealer Management Guide: https://help.salesforce.com/s/articleView?id=sf.auto_dealer_mgmt.htm',
            '',
            ...salesforceReferences(),
            ...getSharedSectionLines('automotive'),
            '',
            ...interactionPreferences('Automotive Cloud configuration'),
        ].join('\n');
    },
};
//# sourceMappingURL=automotive.js.map