/*
 * 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 { generateLoyaltyWorkflows } from '../generators/workflows/loyalty.js';
import { consultativeDesign, deployment, documentationStandards, flsAndCrudEnforcement, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, nativeConfigurationFirst, salesforceReferences, semanticCommits, testCoverageStandards, } from './shared-sections.js';
export const loyaltyProfile = {
    id: 'loyalty',
    label: 'Loyalty Management',
    ruleFile: 'loyalty-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/LoyaltyProgram')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/LoyaltyProgramMember')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/TransactionJournal')));
    },
    workflows: generateLoyaltyWorkflows,
    ruleContent() {
        return [
            '---',
            'description: Loyalty Management Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# Loyalty Management Standards',
            '',
            '> Role: Loyalty Management Developer / Consultant — Salesforce Professional Services.',
            '> Loyalty Management is a Salesforce industry solution for designing, managing, and optimizing loyalty programs. All standards here apply **in addition to** general Apex and LWC rules.',
            '',
            ...consultativeDesign('Loyalty program design and configuration decisions'),
            '',
            ...nativeConfigurationFirst(),
            '',
            '## Loyalty Management Data Model (CRITICAL)',
            '',
            '### Core Concepts',
            '- **Programs:** Top-level loyalty program definitions with branding, rules, and tier structures.',
            '- **Tiers:** Membership levels with qualification criteria, benefits, and transition rules.',
            '- **Members:** Individual participants enrolled in a loyalty program with tier status and currency balances.',
            '- **Points/Currency:** Loyalty currencies (points, miles, credits) earned and redeemed by members.',
            '- **Promotions:** Targeted campaigns that award bonus points, multipliers, or special benefits.',
            '- **Vouchers:** Redeemable certificates issued to members as rewards or promotional incentives.',
            '',
            '### Key Objects',
            '| Object | API Name | Purpose |',
            '|--------|----------|---------|',
            '| Loyalty Program | `LoyaltyProgram` | Program definition with name, status, and configuration |',
            '| Loyalty Program Member | `LoyaltyProgramMember` | Member enrollment linking Contact/Account to a program |',
            '| Loyalty Member Tier | `LoyaltyMemberTier` | Current and historical tier assignments for a member |',
            '| Loyalty Member Currency | `LoyaltyMemberCurrency` | Point/currency balances (earned, redeemed, expired, available) |',
            '| Transaction Journal | `TransactionJournal` | Master transaction record (earn, redeem, transfer, expire) |',
            '| Transaction Journal Entry | `TransactionJournalEntry` | Line-item detail within a transaction (per currency/product) |',
            '| Loyalty Promotion | `LoyaltyPromotion` | Promotion campaign with eligibility rules and reward actions |',
            '| Voucher | `Voucher` | Issued voucher instance with status, expiration, and redemption tracking |',
            '| Voucher Definition | `VoucherDefinition` | Template for voucher issuance (value, validity, terms) |',
            '| Benefit Type | `BenefitType` | Catalog of available benefits (discounts, upgrades, access) |',
            '| Benefit Action | `BenefitAction` | Concrete benefit assignment triggered by tier or promotion |',
            '',
            '## Program Design',
            '- **Point-Based Programs:** Members earn and redeem a single currency (e.g., "Reward Points").',
            '- **Tier-Based Programs:** Members progress through tiers (Bronze → Silver → Gold → Platinum) based on activity.',
            '- **Multi-Currency Programs:** Support multiple currencies (points + miles + credits) with independent earn/redeem rules.',
            '- **Partner Programs:** Allow earning/redemption across partner brands via shared program or coalition model.',
            '- **Hybrid Programs:** Combine tier progression with multi-currency earning for complex loyalty ecosystems.',
            '- Define program structure in Setup → Loyalty Management → Loyalty Programs before writing any code.',
            '',
            '## Tier Management',
            '- **Qualification Rules:** Define tier qualification based on earn-based (points earned in period) or spend-based (transaction value) criteria.',
            '- **Tier Transitions:** Configure upgrade thresholds and downgrade rules (immediate vs. period-end evaluation).',
            '- **Grace Periods:** Allow members to retain tier status for a configurable period after falling below threshold.',
            '- **Tier Benefits:** Assign benefit actions per tier (e.g., Gold members get 2x multiplier, free shipping).',
            '- **Tier Periods:** Define qualification periods (calendar year, rolling 12 months, custom period).',
            '- Use `LoyaltyMemberTier` records to track current and historical tier assignments.',
            '',
            '## Earning Rules',
            '- **Accrual Events:** Define which transactions trigger point earning (purchase, referral, engagement, check-in).',
            '- **Multipliers:** Configure tier-based or promotion-based earn multipliers (e.g., Gold = 1.5x base points).',
            '- **Bonus Point Campaigns:** Time-limited campaigns that award extra points on qualifying transactions.',
            '- **Partner Earn Rules:** Define earn rates for partner transactions with conversion ratios.',
            '- **Earn Caps:** Set maximum earning limits per transaction, per day, or per period to prevent gaming.',
            '- Process earning via `TransactionJournal` records — never manipulate `LoyaltyMemberCurrency` directly.',
            '',
            '## Redemption',
            '- **Redemption Catalog:** Define available rewards with point costs (products, discounts, experiences).',
            '- **Point Values:** Set monetary value per point for flexible redemption (e.g., 100 points = $1).',
            '- **Partial Redemption:** Allow members to use points + cash for purchases above their balance.',
            '- **Expiration Policies:** Configure point expiration rules (rolling expiration, fixed date, activity-based refresh).',
            '- **Redemption Locks:** Prevent redemption of points earned in the current qualifying period if needed for tier status.',
            '- All redemptions must create `TransactionJournal` entries with type "Redeem" for audit trail.',
            '',
            '## Promotions',
            '- **Targeted Promotions:** Define member segments eligible for promotion (by tier, activity, demographics).',
            '- **Member Segments:** Use Data Cloud or SOQL-based segments to target promotion audiences.',
            '- **Double-Point Events:** Time-limited promotions that multiply base earn rate across all transactions.',
            '- **Gamification:** Badge awards, streak bonuses, and challenge completions as promotion mechanics.',
            '- **Promotion Stacking:** Define whether promotions can combine (additive vs. best-offer-wins).',
            '- Configure promotions via `LoyaltyPromotion` with start/end dates and eligibility criteria.',
            '',
            '## Voucher Management',
            '- **Voucher Definitions:** Template records defining voucher value, validity period, redemption rules, and terms.',
            '- **Issuance Rules:** Automatic issuance on tier upgrade, promotion trigger, or manual award by agent.',
            '- **Redemption Tracking:** Track voucher usage with status transitions (Issued → Redeemed → Expired).',
            '- **Expiration:** Configure voucher validity periods with automatic expiration processing.',
            '- **Partial Use:** Define whether vouchers support partial redemption or are single-use only.',
            '- Link vouchers to members via the `Voucher` object with `VoucherDefinition` as the template.',
            '',
            '## Integration Patterns',
            '- **POS Systems:** Real-time earn/redeem via REST API or Platform Events for in-store transactions.',
            '- **E-Commerce Platforms:** Webhook-based integration for online purchase earning and cart-level redemption.',
            '- **Partner Loyalty Networks:** API-based point transfer and earn/redeem across partner programs.',
            '- **CDP for Segmentation:** Connect Data Cloud unified profiles for promotion targeting and personalization.',
            '- **Marketing Cloud:** Trigger journey entries on tier changes, point milestones, or voucher issuance.',
            '- **Financial Systems:** Reconcile point liability with finance via scheduled batch exports.',
            '- Use Named Credentials for all external system authentication — never hardcode API keys.',
            '',
            '## Security & Privacy',
            '- **Member Data Privacy:** Loyalty member data is PII — apply appropriate FLS and sharing rules.',
            '- **PII Protection:** Mask member identifiers in logs and external API payloads.',
            '- **Fraud Detection:** Monitor for gaming patterns — rapid point accumulation, suspicious redemption velocity, account cycling.',
            '- **Point Hoarding Detection:** Alert on members accumulating abnormal balances without redemption activity.',
            '- **Access Controls:** Restrict point adjustment capabilities to authorized roles via Permission Sets.',
            '- **Audit Trail:** All point balance changes must flow through `TransactionJournal` — never update currency records directly.',
            '',
            '## Testing',
            '- **Test Factories:** Create reusable factories for `LoyaltyProgram`, `LoyaltyProgramMember`, `LoyaltyMemberCurrency`, and `TransactionJournal`.',
            '- **Tier Qualification Tests:** Verify tier upgrade/downgrade logic with boundary values (exactly at threshold, one point below).',
            '- **Earn/Redeem Tests:** Validate point calculations with multipliers, caps, and promotion stacking.',
            '- **Expiration Tests:** Test point expiration batch processing with known dates and balances.',
            '- **Voucher Lifecycle Tests:** Cover issuance, redemption, partial use, and expiration scenarios.',
            '- **Fraud Scenario Tests:** Verify detection logic triggers on known gaming patterns.',
            ...testCoverageStandards(),
            '',
            ...flsAndCrudEnforcement(),
            '',
            ...documentationStandards(),
            '',
            ...deployment(),
            '',
            ...semanticCommits(),
            '',
            ...generatedPromptsProtocol(),
            '',
            '## Loyalty Management References',
            '- Loyalty Management Developer Guide: https://developer.salesforce.com/docs/atlas.en-us.loyalty.meta/loyalty/',
            '- Loyalty Management Overview: https://help.salesforce.com/s/articleView?id=sf.loyalty_management.htm',
            '- Loyalty Management Data Model: https://developer.salesforce.com/docs/atlas.en-us.loyalty.meta/loyalty/loyalty_data_model.htm',
            '',
            ...salesforceReferences(),
            ...getSharedSectionLines('loyalty'),
            '',
            ...interactionPreferences('Loyalty program configuration'),
        ].join('\n');
    },
};
//# sourceMappingURL=loyalty.js.map