/*
 * 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 { generatePublicSectorWorkflows } from '../generators/workflows/public-sector.js';
import { consultativeDesign, deployment, documentationStandards, flsAndCrudEnforcement, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, nativeConfigurationFirst, salesforceReferences, semanticCommits, testCoverageStandards, } from './shared-sections.js';
export const publicSectorProfile = {
    id: 'public-sector',
    label: 'Public Sector Solutions',
    ruleFile: 'public-sector-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/RegulatoryTrxnFee')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/BusinessLicenseApplication')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/PublicComplaint')));
    },
    workflows: generatePublicSectorWorkflows,
    ruleContent() {
        return [
            '---',
            'description: Public Sector Solutions Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# Public Sector Solutions Standards',
            '',
            '> Role: Public Sector Developer / Consultant — Salesforce Professional Services.',
            '> Public Sector Solutions provides industry-specific objects and processes for government agencies. All standards here apply **in addition to** general Apex and LWC rules.',
            '',
            ...consultativeDesign('Public Sector data model and configuration decisions'),
            '',
            ...nativeConfigurationFirst(),
            '',
            '## Public Sector Data Model (CRITICAL)',
            '- **Public Sector Solutions** provides out-of-the-box objects for Licensing & Permitting, Inspections, Grants Management, and Constituent Services.',
            '- **Never create custom objects that duplicate native Public Sector objects.** Use the standard data model and extend with custom fields using a project prefix.',
            '- **OmniScript for application intake.** Use guided digital forms for citizen-facing processes — never require paper-only workflows when digital alternatives exist.',
            '',
            '### Core Public Sector Objects',
            '| Object | API Name | Purpose |',
            '|--------|----------|---------|',
            '| Business License Application | `BusinessLicenseApplication` | License/permit application intake and review |',
            '| Business License | `BusinessLicense` | Issued license/permit with expiration tracking |',
            '| Regulatory Transaction Fee | `RegulatoryTrxnFee` | Fees, fines, and penalties associated with applications or violations |',
            '| Inspection Type | `InspectionType` | Templates defining inspection categories and checklists |',
            '| Inspection | `Inspection` | Individual inspection execution records |',
            '| Visit | `Visit` | Scheduled field visits for inspections or assessments |',
            '| Public Complaint | `PublicComplaint` | Citizen-submitted complaints and service requests |',
            '| Regulatory Code | `RegulatoryCode` | Applicable laws, ordinances, and regulations |',
            '| Regulatory Code Violation | `RegulatoryCodeViolation` | Documented violations of regulatory codes |',
            '',
            '## Licensing & Permitting',
            '- **Application lifecycle:** Draft → Submitted → Under Review → Approved/Denied → Issued → Expired/Renewed.',
            '- Use `BusinessLicenseApplication` for all intake. Set `ApplicationType` to differentiate: New, Renewal, Amendment.',
            '- `BusinessLicense` is created only upon approval — never pre-create licenses for pending applications.',
            '- Fee calculation via `RegulatoryTrxnFee`: link fees to the application, track payment status (Assessed → Paid → Waived → Refunded).',
            '- Renewal automation: scheduled Flow checks `BusinessLicense.ExpirationDate` and triggers renewal notices.',
            '- **Never bypass the approval process** — all license issuance must go through the configured approval workflow.',
            '',
            '## Inspections',
            '- **Inspection scheduling:** Use `Visit` records for scheduling; `Inspection` records for execution.',
            '- `InspectionType` defines the checklist template — checklist items are generated from the type on inspection start.',
            '- Inspector workflow: Scheduled → In Progress → Completed → Follow-Up Required.',
            '- Failed checklist items auto-generate `RegulatoryCodeViolation` records via Flow.',
            '- Mobile inspections: configure offline sync for `Inspection`, `Visit`, and checklist data.',
            '- **Re-inspections:** When corrective action is submitted, auto-schedule a follow-up `Visit`.',
            '',
            '## Grants Management',
            '- Model grant programs as custom metadata or a dedicated object depending on complexity.',
            '- Grant application intake follows the same OmniScript pattern as licensing.',
            '- Track disbursements via `RegulatoryTrxnFee` with `FeeType` = "Disbursement" (credit transactions).',
            '- Reporting requirements: scheduled reports on fund utilization, grantee compliance, milestone completion.',
            '- **Segregation of duties:** Grant reviewers must not be the same users who approve disbursements.',
            '',
            '## Constituent Services',
            '- **311-style case management:** Use `PublicComplaint` for citizen service requests and complaints.',
            '- Route via Omni-Channel to appropriate department queues (Public Works, Code Enforcement, Utilities).',
            '- Constituent portals (Experience Cloud): enable self-service for status tracking, document submission, payment.',
            '- **Response SLAs:** Configure Entitlements and Milestones on `PublicComplaint` for response time tracking.',
            '- Knowledge Base: publish FAQ and how-to articles for common constituent questions.',
            '',
            '## Regulatory Compliance',
            '- `RegulatoryCode` records define the applicable regulations — link to inspection types and violation categories.',
            '- `RegulatoryCodeViolation` tracks: violation description, severity (Critical/Major/Minor), corrective action deadline, resolution status.',
            '- Penalty assessment: unresolved violations past deadline generate `RegulatoryTrxnFee` penalty records.',
            '- Escalation path: repeated violations → license suspension → revocation workflow.',
            '- **Code enforcement:** Link violations to the facility `Account` and the responsible `Contact` for notification.',
            '',
            '## Document Management',
            '- Application attachments: use `ContentDocumentLink` to associate files with `BusinessLicenseApplication`.',
            '- Permit PDF generation: use Document Generation templates (Flow action) to produce official permit documents.',
            '- Digital signatures: integrate DocuSign or Adobe Sign via Named Credential for permit signing workflows.',
            '- File type restrictions: enforce allowed MIME types (PDF, JPG, PNG) on portal upload components.',
            '- Retention policies: configure Content Lifecycle rules for government record retention compliance.',
            '',
            '## Integration Patterns',
            '### Payment Gateways',
            '- Integrate payment processing (Stripe, PayPal Government, US Bank) via Named Credential callouts.',
            '- Never store credit card numbers in Salesforce — use tokenized payment references only.',
            '- Reconcile payments via Platform Events: payment gateway → Platform Event → Flow updates `RegulatoryTrxnFee.Status`.',
            '',
            '### GIS / Mapping',
            '- Store facility coordinates using Geolocation fields on Account.',
            '- Integrate GIS services (Esri ArcGIS, Google Maps) for inspection route optimization.',
            '- Display facility locations on portal maps using LWC with map components.',
            '',
            '### Legacy System Migration',
            '- Use MuleSoft or Data Loader for bulk migration of historical licenses, inspections, and violations.',
            '- Maintain legacy system IDs as external ID fields for cross-reference.',
            '- Validate data integrity post-migration: record counts, relationship integrity, date accuracy.',
            '',
            '## Accessibility (CRITICAL)',
            '- **WCAG 2.1 AA compliance** is mandatory for all citizen-facing portals and applications.',
            '- **Section 508** compliance for all government employee interfaces.',
            '- Color contrast: minimum 4.5:1 for normal text, 3:1 for large text.',
            '- Keyboard navigation: all interactive elements must be keyboard-accessible.',
            '- Screen reader compatibility: use ARIA labels, semantic HTML, and SLDS components.',
            '- Form accessibility: associate labels with inputs, provide error descriptions, use fieldset/legend for groups.',
            '- Touch targets: minimum 44x44px for mobile interactions.',
            '- Test with assistive technologies: VoiceOver (macOS/iOS), NVDA (Windows), TalkBack (Android).',
            '',
            '## Security',
            '- **FedRAMP considerations:** Salesforce Government Cloud (GovCloud) for agencies requiring FedRAMP High authorization.',
            '- **PII handling:** Constituent personal data (SSN, DOB, address) must use Platform Encryption (Shield).',
            '- **Data residency:** Verify data center location meets agency requirements (US-only for federal).',
            '- **Guest user security:** Lock down Experience Cloud guest user profiles — no access to PII or internal records.',
            '- **Sharing model:** Use Private OWD for constituent data; share via role hierarchy and sharing rules per department.',
            '- **Audit trail:** Enable Field Audit Trail for sensitive fields (license status changes, fee modifications, violation resolutions).',
            '- **Session security:** Enforce MFA for all internal users; configure session timeout per security policy.',
            '',
            '## Testing',
            '- **Test factories for Public Sector objects:** Create reusable `TestDataFactory` methods for:',
            '  - `BusinessLicenseApplication` with various statuses and application types',
            '  - `BusinessLicense` with expiration dates (active, expired, near-expiry)',
            '  - `Inspection` and `Visit` records with linked `InspectionType`',
            '  - `PublicComplaint` with different categories and severity levels',
            '  - `RegulatoryCodeViolation` with corrective action deadlines',
            '- Assign Public Sector permission sets to test users in `@TestSetup`.',
            '- Test approval workflows end-to-end: submit → approve → verify license creation.',
            '- Test fee calculations: verify correct `RegulatoryTrxnFee` amounts per license type.',
            '- Test violation escalation: verify penalties generate for overdue corrective actions.',
            ...testCoverageStandards(),
            '',
            ...flsAndCrudEnforcement(),
            '',
            ...documentationStandards(),
            '',
            ...deployment(),
            '',
            ...semanticCommits(),
            '',
            ...generatedPromptsProtocol(),
            '',
            '## Public Sector References',
            '- Public Sector Solutions Developer Guide: https://developer.salesforce.com/docs/atlas.en-us.public_sector.meta/public_sector/',
            '- Public Sector Object Reference: https://developer.salesforce.com/docs/atlas.en-us.public_sector_object_reference.meta/public_sector_object_reference/',
            '- Licensing & Permitting Guide: https://help.salesforce.com/s/articleView?id=sf.psc_licensing_permitting.htm',
            '',
            ...salesforceReferences(),
            ...getSharedSectionLines('public-sector'),
            '',
            ...interactionPreferences('Public Sector configuration'),
        ].join('\n');
    },
};
//# sourceMappingURL=public-sector.js.map