/*
 * 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 { generateMediaWorkflows } from '../generators/workflows/media.js';
import { consultativeDesign, deployment, documentationStandards, flsAndCrudEnforcement, generatedPromptsProtocol, getSharedSectionLines, interactionPreferences, nativeConfigurationFirst, salesforceReferences, semanticCommits, testCoverageStandards, } from './shared-sections.js';
export const mediaProfile = {
    id: 'media',
    label: 'Media Cloud',
    ruleFile: 'media-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/MediaChannel')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/AdServerIntegration')) ||
            existsSync(join(cwd, 'force-app/main/default/objects/MediaPlan')));
    },
    workflows: generateMediaWorkflows,
    ruleContent() {
        return [
            '---',
            'description: Media Cloud Standards',
            'globs:',
            'alwaysApply: true',
            '---',
            '',
            '# Media Cloud Standards',
            '',
            '> Role: Media Cloud Developer / Consultant — Salesforce Professional Services.',
            '> Media Cloud is a Salesforce industry solution for media companies. All standards here apply **in addition to** general Apex and LWC rules.',
            '',
            ...consultativeDesign('Media Cloud data model and configuration decisions'),
            '',
            ...nativeConfigurationFirst(),
            '',
            '## Media Cloud Data Model (CRITICAL)',
            '- **Media Cloud covers four core domains:** Ad Sales, Subscription Management, Content Distribution, and Audience Segmentation.',
            '- **Never create custom objects that duplicate standard Media Cloud objects.** The managed data model is the system of record for media operations.',
            '- **Always check existing Media Cloud configuration** before proposing custom metadata or objects.',
            '',
            '### Core Media Cloud Objects',
            '| Object | API Name | Purpose |',
            '|--------|----------|---------|',
            '| Media Channel | `MediaChannel` | Distribution channels (TV, digital, print, radio, OTT) |',
            '| Media Plan | `MediaPlan` | Campaign media plans linking advertisers to inventory |',
            '| Ad Space | `AdSpace` | Available advertising inventory units |',
            '| Ad Space Specification | `AdSpaceSpecification` | Technical specs for ad placements (dimensions, format, duration) |',
            '| Subscription Plan | `SubscriptionPlan` | Subscriber plan definitions (tiers, pricing, entitlements) |',
            '| Subscriber Profile | `SubscriberProfile` | Individual subscriber records with lifecycle state |',
            '| Content Distribution | `ContentDistribution` | Content scheduling and distribution across channels |',
            '| Ad Server Integration | `AdServerIntegration` | External ad server connection configuration |',
            '',
            '## Ad Sales',
            '- **Media Plan creation:** Always associate media plans with an Account (advertiser) and Campaign.',
            '  A media plan contains one or more ad space allocations with date ranges, CPM/CPP rates, and impressions targets.',
            '- **Ad Space inventory:** Model available inventory as `AdSpace` records linked to `MediaChannel`.',
            '  Each ad space has specifications (`AdSpaceSpecification`) defining format, dimensions, duration, and placement rules.',
            '- **Proposal generation:** Use Industries CPQ for media proposals.',
            '  Generate proposals from media plans with rate card pricing, package discounts, and value-added placements.',
            '- **Campaign management:** Link media plans to standard Campaign records for ROI tracking.',
            '  Track delivery (impressions served, clicks, conversions) against plan targets.',
            '- **Rate cards:** Configure rate cards per channel, daypart, and audience segment.',
            '  Rate cards drive automatic pricing in proposal generation — never hardcode rates in Apex.',
            '',
            '## Subscription Management',
            '- **Plan configuration:** Define subscription plans with tiers (Basic, Standard, Premium),',
            '  billing frequencies (monthly, annual), and feature entitlements per tier.',
            '- **Subscriber lifecycle:** Model the complete lifecycle: Trial → Active → Suspended → Churned.',
            '  Use Record-Triggered Flows for state transitions — never trigger logic directly on managed objects.',
            '- **Entitlements:** Link subscription plans to content entitlements.',
            '  Subscribers access content based on their active plan tier and add-on purchases.',
            '- **Billing integration:** Integrate with billing systems via Platform Events or Named Credential callouts.',
            '  Never store payment card data in Salesforce — use tokenized references only.',
            '',
            '## Audience Management',
            '- **Segment definition:** Define audience segments based on demographics, viewing behavior, and content preferences.',
            '  Segments drive ad targeting and rate card pricing (premium audiences command higher CPMs).',
            '- **First-party data:** Leverage subscriber data as first-party audience data for ad sales.',
            '  Ensure consent management is in place before using subscriber data for advertising purposes.',
            '- **Audience targeting:** Match ad space inventory to audience segments for campaign delivery.',
            '  Use reach estimation to forecast available impressions per segment before proposal generation.',
            '- **Reach estimation:** Calculate projected impressions based on historical delivery data,',
            '  channel capacity, and audience overlap. Surface estimates in the proposal workflow.',
            '',
            '## Content Operations',
            '- **Content scheduling:** Use `ContentDistribution` to schedule content across channels with date/time slots.',
            '  Respect channel-specific blackout windows and contractual exclusivity periods.',
            '- **Distribution channels:** Model each distribution channel (linear TV, OTT, web, mobile, social) as a `MediaChannel`.',
            '  Channel attributes drive content formatting requirements and delivery mechanisms.',
            '- **Rights management:** Track content rights windows (start date, end date, territory, platform).',
            '  Block scheduling outside rights windows — enforce via validation rules or Before Save flows.',
            '',
            '## Integration Patterns',
            '- **Ad server integration (Google Ad Manager, FreeWheel):**',
            '  Use `AdServerIntegration` records to configure external ad server connections.',
            '  Sync ad space availability, delivery reports, and campaign trafficking via scheduled Apex or Platform Events.',
            '- **CRM to ad tech:** Push audience segments and campaign metadata to DSPs/SSPs via Named Credential callouts.',
            '  Use Queueable Apex for bulk sync operations to respect governor limits.',
            '- **CDN integration:** Content delivery metadata (URLs, thumbnails, manifests) syncs from CDN systems.',
            '  Store CDN references — never store actual media files in Salesforce.',
            '',
            '## Industries CPQ for Media',
            '- Use Industries CPQ for media proposal generation and rate card pricing.',
            '- Configure product catalog with media-specific attributes: channel, daypart, format, audience segment.',
            '- Rate card rules drive automatic price calculation based on placement characteristics.',
            '- Support package deals (multi-channel bundles) and value-added placements (bonus spots).',
            '- Generate IOPs (Insertion Order Proposals) from approved media plans.',
            '',
            '## Security',
            '- **Subscriber PII:** Subscriber personal data is sensitive. Apply field-level encryption on PII fields.',
            '  Use Shield Platform Encryption for subscriber email, phone, and address fields.',
            '- **Content rights access control:** Restrict content rights data to authorized content operations teams.',
            '  Use Permission Sets and sharing rules — never expose rights windows to advertiser portal users.',
            '- **Partner portal sharing:** Advertisers and agencies access their own media plans via Experience Cloud.',
            '  Configure sharing rules to scope visibility to owned records only. Use `with sharing` on all portal-facing Apex.',
            '',
            '## Testing Media Cloud',
            '- **Use TestDataFactory** to create media plans, ad spaces, and subscriber records in test setup.',
            '- Create test factories for:',
            '  - `MediaChannel` with associated `AdSpace` and `AdSpaceSpecification` records',
            '  - `MediaPlan` with linked ad space allocations and rate card entries',
            '  - `SubscriberProfile` with active `SubscriptionPlan` associations',
            '  - `ContentDistribution` records with valid scheduling windows',
            '- Test ad server integration with `Test.setMock(HttpCalloutMock.class, ...)` for external callouts.',
            '- Validate subscriber lifecycle transitions with multiple test scenarios (trial→active, active→churned).',
            ...testCoverageStandards(),
            '',
            ...flsAndCrudEnforcement(),
            '',
            ...documentationStandards(),
            '',
            ...deployment(),
            '',
            ...semanticCommits(),
            '',
            ...generatedPromptsProtocol(),
            '',
            '## Media Cloud References',
            '- Media Cloud Developer Guide: https://developer.salesforce.com/docs/atlas.en-us.media_cloud.meta/media_cloud/',
            '- Media Cloud Overview: https://help.salesforce.com/s/articleView?id=sf.media_cloud_overview.htm',
            '',
            ...salesforceReferences(),
            ...getSharedSectionLines('media'),
            '',
            ...interactionPreferences('Media Cloud configuration'),
        ].join('\n');
    },
};
//# sourceMappingURL=media.js.map