/*
 * 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 generateMediaWorkflows(version) {
    return {
        'ad-sales-setup.md': workflow(version, 'Ad Sales Setup', `
## 1. Gather Requirements

Ask:
- **Channels:** Which media channels does the org sell advertising on? (Linear TV, Digital, Print, Radio, OTT, Social)
- **Inventory model:** How is ad space inventory structured? By program, daypart, page, or custom unit?
- **Rate card structure:** Are rates based on CPM, CPP, flat fee, or hybrid? Do rates vary by audience segment?
- **Proposal workflow:** Who creates proposals? Is there an approval process before sending to advertisers?
- **Ad server:** Which external ad server is used? (Google Ad Manager, FreeWheel, custom)
- **Package deals:** Are multi-channel bundles or value-added placements offered?

Check \`force-app/main/default/objects/\` for existing Media Cloud object customizations before adding new fields.

## 2. Configure Media Channels

1. Create \`MediaChannel\` records for each distribution channel (e.g., "ACME TV Linear", "ACME Digital", "ACME OTT").
2. Set channel attributes: type, audience reach, available dayparts, content format.
3. Link channels to the appropriate business unit or brand Account.
4. Verify channel records are visible to the ad sales team via sharing rules.

## 3. Set Up Ad Space Inventory

### Ad Space Records
1. Create \`AdSpace\` records for each sellable inventory unit.
2. Link each ad space to its parent \`MediaChannel\`.
3. Define availability windows (start date, end date, blackout dates).
4. Set capacity fields: total available impressions, maximum bookings per slot.

### Ad Space Specifications
1. Create \`AdSpaceSpecification\` records defining technical requirements:
   - Format (video, display, audio, native)
   - Dimensions (e.g., 1920x1080, 300x250)
   - Duration (15s, 30s, 60s for video/audio)
   - Placement rules (pre-roll, mid-roll, billboard, interstitial)
2. Associate specifications with ad space records.

## 4. Configure Rate Cards

1. Define rate card entries per channel, daypart, and audience segment.
2. Set pricing model per entry: CPM (cost per mille), CPP (cost per point), flat rate.
3. Configure seasonal adjustments (upfronts, scatter market, holiday premiums).
4. Set up package pricing for multi-channel bundles.
5. Rate cards feed Industries CPQ — never hardcode pricing in Apex or Flow.

## 5. Set Up Proposal Generation

1. Configure Industries CPQ product catalog with media-specific product entries.
2. Map ad space inventory to CPQ products with rate card-driven pricing.
3. Define quote templates for Insertion Order Proposals (IOPs).
4. Configure approval workflows for proposals exceeding discount thresholds.
5. Set up e-signature integration for advertiser acceptance.

## 6. Configure Ad Server Integration

1. Create \`AdServerIntegration\` records for each external ad server connection.
2. Configure Named Credentials for authentication (OAuth 2.0 or API key).
3. Set up scheduled Apex or Platform Events for:
   - Pushing booked campaigns to the ad server
   - Pulling delivery reports (impressions, clicks, completions)
   - Syncing inventory availability
4. Test integration with \`Test.setMock(HttpCalloutMock.class, ...)\`.

## 7. Deploy Ad Sales Configuration

\`\`\`bash
sf project deploy start \\
  --source-dir force-app/main/default/objects/MediaChannel \\
  --source-dir force-app/main/default/objects/AdSpace \\
  --source-dir force-app/main/default/objects/AdSpaceSpecification \\
  --source-dir force-app/main/default/objects/MediaPlan \\
  --source-dir force-app/main/default/objects/AdServerIntegration \\
  --target-org <alias>
\`\`\`

Verify in the target org:
- Media channels display with correct attributes
- Ad space inventory is linked to channels with valid specifications
- Rate cards drive correct pricing in proposal generation
- Ad server integration syncs delivery data on schedule
`),
        'subscription-management-setup.md': workflow(version, 'Subscription Management Setup', `
## 1. Gather Requirements

Ask:
- **Plan tiers:** What subscription tiers exist? (Free, Basic, Standard, Premium, Enterprise)
- **Billing frequency:** Monthly, quarterly, annual, or mixed?
- **Trial model:** Is there a free trial period? Duration? Auto-conversion to paid?
- **Entitlements:** What content or features does each tier unlock?
- **Billing system:** Which external billing system is used? (Zuora, Stripe, custom)
- **Churn management:** Are there retention offers or downgrade paths before cancellation?
- **Family/group plans:** Can multiple subscribers share a single plan?

Check \`force-app/main/default/objects/\` for existing subscription-related customizations.

## 2. Configure Subscription Plans

1. Create \`SubscriptionPlan\` records for each tier:
   - Plan name, description, tier level
   - Billing frequency (monthly, annual)
   - Base price and currency
   - Trial duration (if applicable)
   - Feature entitlements included
2. Define add-on plans for premium features (e.g., ad-free, 4K streaming, multi-device).
3. Set plan availability: active, sunset (no new signups), archived.
4. Configure upgrade/downgrade paths between tiers.

## 3. Set Up Subscriber Lifecycle

### Lifecycle States
Model the subscriber journey with these states on \`SubscriberProfile\`:
- **Trial** — free evaluation period, limited features
- **Active** — paying subscriber with full tier entitlements
- **Suspended** — payment failed, grace period before cancellation
- **Churned** — cancelled or expired subscription
- **Win-back** — previously churned, targeted for re-acquisition

### Lifecycle Automation (Record-Triggered Flows)
1. **Trial → Active:** Triggered on successful first payment confirmation (Platform Event from billing).
2. **Active → Suspended:** Triggered when payment fails. Set grace period (7 days default).
3. **Suspended → Active:** Triggered on successful retry payment.
4. **Suspended → Churned:** Triggered when grace period expires without payment.
5. **Any → Churned:** Triggered on explicit cancellation request.

Do NOT add triggers directly on managed subscription objects — use Flows exclusively.

## 4. Configure Entitlements

1. Define entitlement records linking subscription plans to content access rights.
2. Map tier levels to content libraries or feature flags:
   - Basic: standard content catalog
   - Standard: standard + premium content
   - Premium: all content + early access + ad-free
3. Configure entitlement checks in content delivery logic.
4. Set up entitlement expiration aligned with subscription billing cycle.

## 5. Billing Integration

### Platform Event Pattern
1. Define Platform Events for billing lifecycle:
   - \`SubscriptionPaymentReceived__e\` — successful payment
   - \`SubscriptionPaymentFailed__e\` — failed payment attempt
   - \`SubscriptionRenewalProcessed__e\` — renewal cycle completed
2. Create Platform Event subscribers (Apex triggers or Flows) to update subscriber state.

### Named Credential Callouts
1. Configure Named Credential for the billing system API.
2. Implement Queueable Apex for bulk subscription operations:
   - Sync new subscribers to billing system
   - Process plan changes (upgrades/downgrades)
   - Handle cancellation requests
3. Never store payment card data in Salesforce — use tokenized billing references only.

## 6. Churn Prevention

1. Configure alerts for subscribers approaching churn triggers:
   - Multiple failed payments
   - Low engagement (no logins in 30 days)
   - Downgrade requests
2. Set up retention offer automation:
   - Discount offers for at-risk subscribers
   - Plan pause option (suspend without cancel)
   - Downgrade to lower tier instead of full cancellation
3. Track win-back eligibility and campaign targeting.

## 7. Deploy Subscription Configuration

\`\`\`bash
sf project deploy start \\
  --source-dir force-app/main/default/objects/SubscriptionPlan \\
  --source-dir force-app/main/default/objects/SubscriberProfile \\
  --source-dir force-app/main/default/flows \\
  --source-dir force-app/main/default/customMetadata \\
  --target-org <alias>
\`\`\`

Verify in the target org:
- Subscription plans display with correct tier attributes and pricing
- Subscriber lifecycle transitions fire correctly on state changes
- Entitlements are granted and revoked based on active plan
- Billing Platform Events trigger the appropriate subscriber state updates
- Churn prevention alerts fire for at-risk subscribers
`),
    };
}
//# sourceMappingURL=media.js.map