/*
 * 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 { generateMapsWorkflows } from '../generators/workflows/maps.js';
import { consultativeDesign, deployment, documentationStandards, flsAndCrudEnforcement, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, nativeConfigurationFirst, salesforceReferences, semanticCommits, testCoverageStandards, } from './shared-sections.js';
export const mapsProfile = {
    id: 'maps',
    label: 'Salesforce Maps',
    ruleFile: 'maps-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/maps__Location__c')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/maps__Route__c')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/maps__Assignment__c')) ||
            existsSync(join(cwd, 'force-app/main/default/installedPackages/maps')));
    },
    workflows: generateMapsWorkflows,
    ruleContent() {
        return [
            '---',
            'description: Salesforce Maps Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# Salesforce Maps Standards',
            '',
            '> Role: Salesforce Maps Developer / Consultant — Salesforce Professional Services.',
            '> Salesforce Maps is a managed package for location intelligence, route optimization, and territory planning. All standards here apply **in addition to** general Apex and LWC rules.',
            '',
            ...consultativeDesign('Maps data model and configuration decisions'),
            '',
            ...nativeConfigurationFirst(),
            '',
            '## Salesforce Maps Data Model (CRITICAL)',
            '',
            '### Core Concepts',
            '- **Location Tracking:** Real-time and historical geolocation of field reps, accounts, and assets.',
            '- **Route Optimization:** Multi-stop routing with travel time estimation, driver constraints, and schedule optimization.',
            '- **Territory Planning:** Geographic territory definition, account assignment optimization, and workload balancing.',
            '- **Live Tracking:** Real-time field rep location monitoring, geofencing, and proximity alerts.',
            '',
            '### Key Objects',
            '| Object | API Name | Purpose |',
            '|--------|----------|---------|',
            '| Location | `maps__Location__c` | Geocoded location record with latitude/longitude coordinates |',
            '| Route | `maps__Route__c` | Planned or completed route with stops, distance, and travel time |',
            '| Assignment | `maps__Assignment__c` | Territory-to-account or territory-to-rep assignment record |',
            '| Territory | Territory Planning objects | Geographic boundary definitions for field coverage |',
            '| Layer | Map Layer configuration | Custom data visualization layers on the map canvas |',
            '| Marker | Map Marker configuration | Visual representation of records on the map |',
            '',
            '## Territory Planning',
            '- **Geographic Territories:** Define territories using geographic boundaries (ZIP codes, states, counties, custom polygons).',
            '- **Account Assignment Optimization:** Automatically assign accounts to territories based on proximity, workload, and business rules.',
            '- **Workload Balancing:** Distribute accounts evenly across reps based on configurable metrics (revenue, visit frequency, account count).',
            '- **Alignment Rules:** Define constraints for territory assignments — rep capacity, travel time limits, account affinity.',
            '- **Scenario Modeling:** Create multiple territory alignment scenarios to compare before committing changes.',
            '- Use the Territory Planning UI in Setup → Salesforce Maps → Territory Planning for configuration.',
            '',
            '## Route Optimization',
            '- **Multi-Stop Routing:** Plan routes with multiple stops optimized for shortest travel time or distance.',
            '- **Travel Time Estimation:** Uses real-time and historical traffic data for accurate drive-time calculations.',
            '- **Schedule Optimization:** Align route stops with appointment windows, business hours, and rep availability.',
            '- **Driver Constraints:** Model constraints like max drive time per day, mandatory breaks, vehicle type limitations.',
            '- **Recurring Routes:** Templates for repeat visits (weekly check-ins, monthly service calls).',
            '- **Route Priorities:** Weight stops by urgency, account tier, or SLA deadlines.',
            '- Never hardcode travel time assumptions — always rely on the Maps routing engine.',
            '',
            '## Live Tracking',
            '- **Real-Time Field Rep Location:** Track rep positions via the Salesforce Maps mobile app.',
            '- **Geofencing:** Define geographic boundaries that trigger alerts when reps enter or exit.',
            '- **Proximity Alerts:** Notify reps when they are near high-priority accounts or open service cases.',
            '- **Check-In/Check-Out:** Automatic logging of visit start/end times based on geofence triggers.',
            '- **Historical Breadcrumbs:** Store location history for route compliance and mileage reporting.',
            '- Respect opt-in consent for tracking — never enable live tracking without explicit user agreement.',
            '',
            '## Data Visualization',
            '- **Custom Map Layers:** Overlay data sets on the map canvas (accounts, opportunities, cases, assets).',
            '- **Heat Maps:** Visualize density or intensity of data points (e.g., revenue concentration, case volume).',
            '- **Clustering:** Group nearby markers at zoom levels to avoid visual clutter.',
            '- **Boundary Overlays:** Display territory, ZIP code, county, or custom polygon boundaries.',
            '- **Color Coding:** Use data-driven marker colors to represent account tier, opportunity stage, or case priority.',
            '- Configure layers in Setup → Salesforce Maps → Map Layers.',
            '',
            '## Integration Patterns',
            '- **Geocoding Services:** Maps uses its own geocoding engine — do NOT call external geocoding APIs for records already in the Maps system.',
            '- **External Mapping APIs:** When integrating third-party mapping data, use Named Credentials for authentication.',
            '- **Fleet Management Systems:** Integrate via Platform Events or REST callouts for real-time vehicle telemetry.',
            '- **ERP / Scheduling Systems:** Sync appointment windows and delivery schedules via middleware (MuleSoft recommended).',
            '- **Data Cloud:** Feed location analytics into Data Cloud for unified customer 360 with geographic context.',
            '',
            '## Managed Package Safety Rules',
            '- **All Maps objects use the `maps__` namespace.** Never create custom objects that shadow Maps functionality.',
            '- **Do NOT add Apex triggers directly on Maps managed objects** (`maps__Location__c`, `maps__Route__c`, etc.).',
            '  Use Record-Triggered Flows or Platform Events for reactive automation.',
            '- **Do NOT delete or rename Maps managed fields.** Extend only — add custom fields with a project prefix.',
            '- **Do NOT override Maps managed page layouts.** Clone them and assign the clone to your Record Type.',
            '- Before each package upgrade, review release notes for breaking changes to the `maps__` namespace.',
            '- Test upgrades in a sandbox before promoting to production.',
            '',
            '## Security & Privacy',
            '- **Location Data Privacy:** Location data is PII — apply appropriate FLS restrictions and sharing rules.',
            '- **GDPR Considerations:** For EU users, ensure location tracking has documented legal basis (consent or legitimate interest).',
            '- **Opt-In Consent:** Live tracking must require explicit user opt-in. Store consent records with timestamps.',
            '- **Data Retention:** Define and enforce retention policies for historical location breadcrumbs.',
            '- **Access Controls:** Restrict live tracking visibility to managers/dispatchers — reps should not see peer locations.',
            '- **Geofence Sensitivity:** Avoid geofences around private residences or sensitive locations unless business-justified.',
            '',
            '## Testing',
            '- **Mock Coordinates:** Use fixed test coordinates (e.g., `37.7749, -122.4194` for San Francisco) in test factories.',
            '- **Never call external geocoding APIs in tests** — use `Test.setMock()` for any callout-dependent logic.',
            '- **Territory Assignments:** Create test territories with known boundaries and verify assignment logic deterministically.',
            '- **Route Calculations:** Mock routing engine responses; do not depend on live routing in unit tests.',
            '- **Geofence Triggers:** Test geofence entry/exit logic with synthetic location updates, not real GPS data.',
            ...testCoverageStandards(),
            '',
            ...flsAndCrudEnforcement(),
            '',
            ...documentationStandards(),
            '',
            ...deployment(),
            '',
            ...semanticCommits(),
            '',
            ...generatedPromptsProtocol(),
            '',
            '## Maps References',
            '- Salesforce Maps Developer Guide: https://developer.salesforce.com/docs/atlas.en-us.salesforce_maps.meta/salesforce_maps/',
            '- Maps Territory Planning: https://help.salesforce.com/s/articleView?id=sf.maps_territory_planning.htm',
            '- Maps Setup Guide: https://help.salesforce.com/s/articleView?id=sf.maps_setup.htm',
            '',
            ...salesforceReferences(),
            ...getSharedSectionLines('maps'),
            '',
            ...interactionPreferences('Maps configuration'),
        ].join('\n');
    },
};
//# sourceMappingURL=maps.js.map