/*
 * 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 { workflow } from '../workflow-generator.js';
export function generateLoyaltyWorkflows(version) {
    return {
        'loyalty-program-setup.md': workflow(version, 'Loyalty Program Setup', `
## 1. Gather Requirements

Ask:
- **Program type:** Point-based, tier-based, or hybrid (tiers + multiple currencies)?
- **Currencies:** How many loyalty currencies? (e.g., points only, or points + miles + credits)
- **Tier structure:** How many tiers? What are the names and qualification thresholds?
- **Qualification criteria:** Earn-based (points earned in period) or spend-based (transaction value)?
- **Tier periods:** Calendar year, rolling 12 months, or custom qualification period?
- **Earning events:** Which actions earn points? (purchase, referral, engagement, check-in, review)
- **Redemption model:** Fixed catalog, flexible point-to-currency conversion, or both?
- **Expiration rules:** Do points expire? (rolling, fixed date, activity-based refresh)

Check \`force-app/main/default/objects/LoyaltyProgram\` for existing program configurations before creating new ones.

## 2. Configure the Program Structure

### Program Definition
1. Navigate to Setup → Loyalty Management → Loyalty Programs.
2. Create the program record:
   - **Name:** The customer-facing program name.
   - **Status:** Draft (keep in Draft until fully configured).
   - **Program Type:** Individual or Coalition (partner program).
3. Define program branding and communication templates.

### Currency Configuration
1. Create \`LoyaltyMemberCurrency\` definitions for each currency type:
   - **Primary Currency:** e.g., "Reward Points" — used for tier qualification and basic redemption.
   - **Secondary Currencies:** e.g., "Bonus Miles", "Status Credits" — earned separately with distinct rules.
2. Set currency properties:
   - Name and display label
   - Decimal precision (0 for whole points, 2 for monetary equivalents)
   - Expiration policy (none, rolling N months, fixed annual reset)
3. Define exchange rates between currencies if transfers are allowed.

### Tier Configuration
1. Create tiers in ascending order:
   - **Base/Bronze:** Entry level — all new members start here.
   - **Silver:** First upgrade threshold (e.g., 1,000 points earned in period).
   - **Gold:** Mid-tier (e.g., 5,000 points earned in period).
   - **Platinum:** Top tier (e.g., 15,000 points earned in period).
2. For each tier, configure:
   - **Qualification threshold:** Points or spend required to reach the tier.
   - **Maintenance threshold:** Points or spend required to retain the tier (can differ from qualification).
   - **Grace period:** Days/months a member retains tier after falling below threshold.
   - **Benefits:** List of \`BenefitAction\` records assigned at this tier level.

## 3. Configure Earning Rules

### Base Earn Rate
1. Define the default earn rate per transaction type:
   - Purchase: 1 point per $1 spent
   - Referral: 500 bonus points per successful referral
   - Engagement: 10 points per activity (check-in, review, survey)
2. Set tier-based multipliers:
   - Bronze: 1.0x (base)
   - Silver: 1.25x
   - Gold: 1.5x
   - Platinum: 2.0x

### Earn Processing
1. Configure \`TransactionJournal\` record creation for each earning event:
   - Journal Type: "Accrual"
   - Link to \`LoyaltyProgramMember\` and \`LoyaltyMemberCurrency\`
   - Populate amount, multiplier applied, and source transaction reference
2. Set up earn caps if required:
   - Per-transaction cap (e.g., max 10,000 points per purchase)
   - Daily cap (e.g., max 50,000 points per day)
   - Period cap (e.g., max 500,000 points per quarter)

### Redemption Rules
1. Define redemption catalog entries:
   - Point cost per reward item
   - Minimum balance required to redeem
   - Redemption availability by tier (some rewards Gold+ only)
2. Configure flexible redemption:
   - Points-to-currency ratio (e.g., 100 points = $1)
   - Minimum redemption amount
   - Partial redemption allowed (yes/no)
3. Set redemption restrictions:
   - Cannot redeem qualifying points in current tier period (optional)
   - Cool-down period between redemptions (optional)

## 4. Configure Tier Transition Logic

### Upgrade Processing
1. Define evaluation schedule:
   - Real-time (upgrade immediately upon reaching threshold)
   - Batch (evaluate nightly or weekly)
2. Configure upgrade actions:
   - Create \`LoyaltyMemberTier\` record with new tier
   - Issue welcome voucher for new tier
   - Send tier upgrade notification (Marketing Cloud journey entry)
   - Assign new \`BenefitAction\` records

### Downgrade Processing
1. Define downgrade evaluation:
   - End of qualification period evaluation
   - Grace period (e.g., retain for 3 months after period end)
2. Configure downgrade actions:
   - Update \`LoyaltyMemberTier\` status
   - Remove tier-specific benefits
   - Send retention communication before downgrade
   - Offer "save" promotion (bonus points to re-qualify)

## 5. Deploy Program Configuration

\`\`\`bash
sf project deploy start \\
  --source-dir force-app/main/default/objects/LoyaltyProgram \\
  --source-dir force-app/main/default/objects/LoyaltyProgramMember \\
  --source-dir force-app/main/default/objects/LoyaltyMemberCurrency \\
  --source-dir force-app/main/default/objects/LoyaltyMemberTier \\
  --source-dir force-app/main/default/objects/TransactionJournal \\
  --target-org <alias>
\`\`\`

Verify in the target org:
- Program record is active with correct tier structure
- Test member enrollment creates proper currency and tier records
- Earn transaction creates TransactionJournal and updates currency balance
- Tier upgrade fires when threshold is reached
- Redemption deducts from currency balance correctly
`),
        'promotions-vouchers-setup.md': workflow(version, 'Promotions & Vouchers Setup', `
## 1. Gather Requirements

Ask:
- **Promotion types:** What kinds of promotions are needed? (double points, bonus award, tier qualification boost)
- **Targeting:** How are eligible members identified? (all members, specific tier, segment, behavior-based)
- **Duration:** Are promotions time-limited events or ongoing program features?
- **Stacking:** Can promotions combine? (additive, multiplicative, best-offer-wins)
- **Voucher use cases:** What triggers voucher issuance? (tier upgrade, birthday, apology, promotion reward)
- **Partner integration:** Do promotions involve partner brands or cross-program earning?

Check existing \`LoyaltyPromotion\` and \`VoucherDefinition\` records before creating duplicates.

## 2. Configure Promotion Campaigns

### Promotion Definition
1. Navigate to Setup → Loyalty Management → Promotions.
2. Create the promotion record:
   - **Name:** Internal reference name and customer-facing display name.
   - **Type:** Points Multiplier, Bonus Award, Tier Qualification Boost, or Custom.
   - **Start Date / End Date:** Campaign active period.
   - **Status:** Draft → Scheduled → Active → Completed.
3. Define the reward action:
   - **Points Multiplier:** e.g., 2x points on all purchases during promotion period.
   - **Bonus Award:** e.g., 1,000 bonus points for first purchase during campaign.
   - **Tier Boost:** e.g., double qualification credits during promotion.

### Eligibility Rules
1. Define member eligibility criteria:
   - **All Members:** No restrictions — promotion applies to entire program.
   - **Tier-Based:** Only Gold and Platinum members eligible.
   - **Segment-Based:** Members in a specific Data Cloud segment (e.g., "at-risk", "high-value").
   - **Behavior-Based:** Members who haven't transacted in 90+ days (win-back).
   - **Opt-In Required:** Members must explicitly enroll in the promotion.
2. Configure exclusions:
   - Members who already benefited from a conflicting promotion.
   - Members in fraud watchlist or restricted status.
3. Set participation limits:
   - Max members per promotion (e.g., first 10,000 to opt in).
   - Max benefit per member (e.g., bonus capped at 5,000 points).

### Stacking Rules
1. Define promotion interaction logic:
   - **Additive:** Multiple promotions combine (2x multiplier + 500 bonus = 2x + 500).
   - **Multiplicative:** Multipliers compound (2x tier × 2x promo = 4x total).
   - **Best-Offer-Wins:** Apply only the single most valuable promotion.
   - **Exclusive:** Promotion cannot combine with any other offer.
2. Set priority order for conflict resolution.
3. Document stacking rules in the program policy for agent reference.

## 3. Configure Voucher Definitions

### Voucher Template Setup
1. Navigate to Setup → Loyalty Management → Voucher Definitions.
2. Create voucher definition records:
   - **Name:** e.g., "Gold Welcome Voucher", "Birthday 20% Off", "Service Recovery $50".
   - **Type:** Discount Percentage, Discount Amount, Free Product, Experience Access.
   - **Value:** The discount amount or percentage.
   - **Validity Period:** Days from issuance until expiration (e.g., 30 days, 90 days).
   - **Terms & Conditions:** Minimum purchase, excluded products, one-per-transaction.

### Issuance Rules
1. Configure automatic issuance triggers:
   - **Tier Upgrade:** Issue welcome voucher when member reaches a new tier.
   - **Birthday:** Issue birthday voucher N days before member's birthday.
   - **Milestone:** Issue voucher when member reaches point milestones (10K, 50K, 100K).
   - **Service Recovery:** Agent-initiated issuance for complaint resolution.
   - **Promotion Reward:** Issue voucher as the reward action of a promotion campaign.
2. Set issuance limits:
   - Max vouchers per member per period (e.g., max 1 birthday voucher per year).
   - Max total vouchers issued per definition (inventory cap).
3. Configure notification on issuance (email, push, SMS via Marketing Cloud).

### Redemption Configuration
1. Define redemption rules:
   - **Single Use:** Voucher is fully consumed on first use.
   - **Multi-Use:** Voucher can be used multiple times until value is depleted.
   - **Partial Redemption:** Remaining value carries forward (e.g., $50 voucher, $30 purchase → $20 remaining).
2. Set redemption channels:
   - In-store (POS integration required)
   - Online (e-commerce checkout integration)
   - Agent-assisted (Service Cloud case context)
3. Configure status transitions:
   - Issued → Active (after notification sent)
   - Active → Partially Redeemed (if multi-use)
   - Active/Partially Redeemed → Fully Redeemed
   - Active → Expired (batch job on expiration date)

## 4. Partner Integration

### Partner Earn Rules
1. Define partner program connections:
   - Partner brand name and program identifier.
   - Earn rate at partner (e.g., 1 point per $2 spent at partner).
   - Settlement terms (how partner compensates for point liability).
2. Configure point transfer:
   - Transfer direction (uni-directional or bi-directional).
   - Conversion ratio (e.g., 1,000 your points = 800 partner miles).
   - Transfer fees (if applicable).
3. Set up API integration for real-time partner transaction processing.

### Partner Promotion Collaboration
1. Define co-branded promotions:
   - Bonus points for partner purchases during campaign.
   - Cross-promotion vouchers (earn at partner, redeem in your program).
2. Configure partner attribution in \`TransactionJournal\`:
   - Source system identifier.
   - Partner reference number.
   - Settlement batch reference.

## 5. Deploy Promotion & Voucher Configuration

\`\`\`bash
sf project deploy start \\
  --source-dir force-app/main/default/objects/LoyaltyPromotion \\
  --source-dir force-app/main/default/objects/VoucherDefinition \\
  --source-dir force-app/main/default/objects/Voucher \\
  --source-dir force-app/main/default/objects/BenefitType \\
  --source-dir force-app/main/default/objects/BenefitAction \\
  --target-org <alias>
\`\`\`

Verify in the target org:
- Promotion applies correct multiplier/bonus to qualifying transactions
- Eligibility rules correctly filter member audience
- Voucher issuance triggers fire on configured events (tier upgrade, birthday)
- Voucher redemption deducts value and updates status
- Expired vouchers are processed by the batch job
- Partner transactions create proper TransactionJournal entries with attribution
`),
    };
}
//# sourceMappingURL=loyalty.js.map