// src/services/serviceCatalog.js

/**
 * Service catalog organized by Provider → Service → Action
 * 
 * Structure:
 * - provider: Ad platform (google, meta, msads)
 * - service: Sub-module/microservice (system, campaigns, reporting, accounts)
 * - action: Specific operation (ping, create, list, get, update, delete)
 */
export const servicesByProvider = {
  gateway: [
    {
      id: 'GatewayPing',
      service: 'system',
      action: 'ping',
      label: 'System: Ping (SQL test)',
      sample: {},
      endpoint: '/api/test/ping',
      method: 'GET'
    },
    // Campaign Wizard operations
    {
      id: 'WizardCreate',
      service: 'wizard',
      action: 'create',
      label: 'Wizard: Create New',
      sample: { name: 'My Test Campaign', url: 'https://example.com' },
      endpoint: '/api/wizard',
      method: 'POST'
    },
    {
      id: 'WizardGet',
      service: 'wizard',
      action: 'get',
      label: 'Wizard: Get by ID',
      sample: { wizardId: 'abc123def456' },
      endpoint: '/api/wizard/{wizardId}',
      method: 'GET'
    },
    {
      id: 'WizardList',
      service: 'wizard',
      action: 'list',
      label: 'Wizard: List All',
      sample: { status: 'draft' },
      endpoint: '/api/wizard',
      method: 'GET'
    },
    {
      id: 'WizardUpdateStep',
      service: 'wizard',
      action: 'updateStep',
      label: 'Wizard: Update Step 4 (Audience)',
      sample: { 
        wizardId: 'abc123def456',
        step: 4,
        data: {
          locations: [{ id: 9061285, name: 'Huntington Beach', type: 'City', radiusMiles: 25 }],
          demographics: { ageRanges: ['AGE_25_34', 'AGE_35_44'], genders: ['MALE', 'FEMALE'] },
          audiences: { affinity: [80001], inMarket: [90012] }
        }
      },
      endpoint: '/api/wizard/{wizardId}/step/{step}',
      method: 'PUT'
    },
    {
      id: 'WizardGetSummary',
      service: 'wizard',
      action: 'getSummary',
      label: 'Wizard: Get Summary (Review)',
      sample: { wizardId: 'abc123def456' },
      endpoint: '/api/wizard/{wizardId}/summary',
      method: 'GET'
    },
    {
      id: 'WizardSubmit',
      service: 'wizard',
      action: 'submit',
      label: 'Wizard: Submit Campaign',
      sample: { wizardId: 'abc123def456', network: 'google' },
      endpoint: '/api/wizard/{wizardId}/submit',
      method: 'POST'
    },
    {
      id: 'WizardDelete',
      service: 'wizard',
      action: 'delete',
      label: 'Wizard: Delete',
      sample: { wizardId: 'abc123def456' },
      endpoint: '/api/wizard/{wizardId}',
      method: 'DELETE'
    },
    // Campaign Intelligence (Gateway → SQL stored proc)
    // These endpoints are Gateway-side; they do NOT call IntelligenceApi.
    // IntelligenceApi is the spend distribution engine (forecast/wizard flow only).
    {
      id: 'IntelligenceHealth',
      service: 'intelligence',
      action: 'health',
      label: 'Intelligence: Campaign Health Overview',
      sample: {},
      endpoint: '/api/intelligence/health',
      method: 'GET'
    },
    {
      id: 'IntelligencePacing',
      service: 'intelligence',
      action: 'pacing',
      label: 'Intelligence: Budget Pacing',
      sample: { initiativeId: 1 },
      endpoint: '/api/intelligence/{initiativeId}/pacing',
      method: 'GET'
    },
    {
      id: 'IntelligenceReport',
      service: 'intelligence',
      action: 'report',
      label: 'Intelligence: Post-Campaign Report',
      sample: { initiativeId: 1 },
      endpoint: '/api/intelligence/{initiativeId}/report',
      method: 'GET'
    },
    {
      id: 'IntelligenceSnapshot',
      service: 'intelligence',
      action: 'snapshot',
      label: 'Intelligence: Record Metric Snapshot (Admin)',
      sample: {
        channelCampaignId: 1,
        date: '2026-03-06',
        impressions: 4200,
        clicks: 87,
        spend: 42.50,
        conversions: 3
      },
      endpoint: '/api/intelligence/snapshot',
      method: 'POST'
    },
    {
      id: 'IntelligenceSnapshotBatch',
      service: 'intelligence',
      action: 'snapshotBatch',
      label: 'Intelligence: Batch Metric Snapshots (Admin)',
      sample: {
        snapshots: [
          { channelCampaignId: 1, date: '2026-03-06', impressions: 4200, clicks: 87, spend: 42.50, conversions: 3 },
          { channelCampaignId: 2, date: '2026-03-06', impressions: 1800, clicks: 34, spend: 18.20, conversions: 1 }
        ]
      },
      endpoint: '/api/intelligence/snapshot/batch',
      method: 'POST'
    }
  ],
  google: [
    // System service
    {
      id: 'Ping',
      service: 'system',
      action: 'ping',
      label: 'System: Ping (GoogleApi round trip)',
      sample: {}
    },
    // Campaigns service
    {
      id: 'CreateCampaign',
      service: 'campaigns',
      action: 'create',
      label: 'Campaigns: Create',
      sample: { name: 'Test Campaign', budgetMicros: 10000000, type: 'Search' }
    },
    {
      id: 'ListCampaigns',
      service: 'campaigns',
      action: 'list',
      label: 'Campaigns: List',
      sample: {}
    },
    {
      id: 'GetCampaign',
      service: 'campaigns',
      action: 'get',
      label: 'Campaigns: Get by ID',
      sample: { campaignId: 'campaigns/123' }
    },
    // Reporting service
    {
      id: 'GetCampaignStats',
      service: 'reporting',
      action: 'campaignStats',
      label: 'Reporting: Campaign Stats',
      sample: { campaignId: 'campaigns/123', startDate: '2026-01-01', endDate: '2026-01-26' }
    },
    {
      id: 'GetAccountStats',
      service: 'reporting',
      action: 'accountStats',
      label: 'Reporting: Account Stats',
      sample: { startDate: '2026-01-01', endDate: '2026-01-26' }
    },
    // Accounts service
    {
      id: 'ListAccessibleCustomers',
      service: 'accounts',
      action: 'list',
      label: 'Accounts: List Accessible Customers',
      sample: {}
    },
    {
      id: 'CreateCustomerClient',
      service: 'accounts',
      action: 'createClient',
      label: 'Accounts: Create Sub-Account (under MCC)',
      sample: { accountName: 'AdPlatform Test Account', currencyCode: 'USD', timeZone: 'America/Los_Angeles' }
    },
    // Audience targeting service
    {
      id: 'GetAudienceSegments',
      service: 'audience',
      action: 'getSegments',
      label: 'Audience: Get All Segments',
      sample: {}
    },
    {
      id: 'SearchGeoTargets',
      service: 'audience',
      action: 'searchGeo',
      label: 'Audience: Search Locations',
      sample: { query: 'Huntington Beach', countryCode: 'US', maxResults: 10 }
    }
  ],
  meta: [
    // System
    {
      id: 'Ping',
      service: 'system',
      action: 'ping',
      label: 'System: Ping (MetaApi round trip)',
      sample: {}
    },
    // Campaigns
    {
      id: 'CreateCampaign',
      service: 'campaigns',
      action: 'create',
      label: 'Campaigns: Create',
      sample: { name: 'Test Meta Campaign', objective: 'Traffic', status: 'Paused' }
    },
    {
      id: 'ListCampaigns',
      service: 'campaigns',
      action: 'list',
      label: 'Campaigns: List',
      sample: { limit: 50 }
    },
    {
      id: 'GetCampaign',
      service: 'campaigns',
      action: 'get',
      label: 'Campaigns: Get by ID',
      sample: { campaignId: '123456789' }
    },
    // Insights
    {
      id: 'GetCampaignInsights',
      service: 'reporting',
      action: 'campaignInsights',
      label: 'Reporting: Campaign Insights',
      sample: { campaignId: '123456789', datePreset: 'last_7d' }
    },
    {
      id: 'GetAccountInsights',
      service: 'reporting',
      action: 'accountInsights',
      label: 'Reporting: Account Insights',
      sample: { datePreset: 'last_30d' }
    },
    // Accounts
    {
      id: 'CreateAdAccount',
      service: 'accounts',
      action: 'createAdAccount',
      label: 'Accounts: Create Ad Account (under BM)',
      sample: { name: 'Test Client Account', currency: 'USD', timezoneId: 1 }
    },
    {
      id: 'ListAdAccounts',
      service: 'accounts',
      action: 'listAdAccounts',
      label: 'Accounts: List BM Ad Accounts',
      sample: {}
    }
  ],
  tiktok: [
    // System
    {
      id: 'Ping',
      service: 'system',
      action: 'ping',
      label: 'System: Ping (TikTokApi round trip)',
      sample: {}
    },
    // Campaigns
    {
      id: 'CreateCampaign',
      service: 'campaigns',
      action: 'create',
      label: 'Campaigns: Create',
      sample: { name: 'Test TikTok Campaign', objective: 'Traffic', budgetMode: 'Day', budget: 50.00, status: 'Disable' }
    },
    {
      id: 'ListCampaigns',
      service: 'campaigns',
      action: 'list',
      label: 'Campaigns: List',
      sample: { pageSize: 50, page: 1 }
    },
    {
      id: 'GetCampaign',
      service: 'campaigns',
      action: 'get',
      label: 'Campaigns: Get by ID',
      sample: { campaignId: '1234567890123456789' }
    },
    // Reporting
    {
      id: 'GetReport',
      service: 'reporting',
      action: 'getReport',
      label: 'Reporting: Integrated Report',
      sample: { reportType: 'BASIC', dataLevel: 'AUCTION_CAMPAIGN', dimensions: ['campaign_id', 'stat_time_day'], metrics: ['spend', 'impressions', 'clicks', 'cpc', 'ctr'] }
    },
    // Accounts (Business Center)
    {
      id: 'CreateAdvertiser',
      service: 'accounts',
      action: 'createAdvertiser',
      label: 'Accounts: Create Advertiser (under BC)',
      sample: { name: 'Test Client', currency: 'USD', timezone: 'America/Los_Angeles', company: 'Test Company' }
    },
    {
      id: 'ListAdvertisers',
      service: 'accounts',
      action: 'listAdvertisers',
      label: 'Accounts: List BC Advertisers',
      sample: {}
    },
    // Fund Management
    {
      id: 'TransferFunds',
      service: 'finance',
      action: 'transfer',
      label: 'Finance: Transfer Funds (BC → Advertiser)',
      sample: { advertiserId: '1234567890123456789', transferType: 'RECHARGE', amount: 100.00 }
    }
  ],
  creative: [
    {
      id: 'Ping',
      service: 'system',
      action: 'ping',
      label: 'System: Ping (Creative round trip)',
      sample: {}
    },
    {
      id: 'AnalyzeUrl',
      service: 'creative',
      action: 'analyzeUrl',
      label: 'Creative: Analyze URL',
      sample: { url: 'https://example.com' }
    },
    {
      id: 'GenerateAssets',
      service: 'creative',
      action: 'generateAssets',
      label: 'Creative: Generate Assets from Analysis',
      sample: {
        analysis: {
          title: 'Example',
          description: 'A sample site',
          headings: ['Welcome'],
          bodySnippet: 'We sell quality products.',
          domain: 'example.com'
        }
      }
    },
    {
      id: 'GetImages',
      service: 'creative',
      action: 'getImages',
      label: 'Creative: Get Images from Analysis',
      sample: {
        analysis: {
          url: 'https://example.com',
          title: 'Example Business',
          metaDescription: 'Quality products and services',
          headings: ['Welcome', 'Our Services'],
          bodySnippet: 'We provide excellent service.',
          inferredCategory: 'Business Services'
        }
      }
    },
    {
      id: 'CreateDraft',
      service: 'creative',
      action: 'createDraft',
      label: 'Creative: Full Pipeline (URL → Draft with Images)',
      sample: { url: 'https://example.com' }
    }
  ],
  intelligence: [
    // System
    {
      id: 'Ping',
      service: 'system',
      action: 'ping',
      label: 'System: Ping (IntelligenceApi round trip)',
      sample: {}
    },
    // Spend Distribution — the core engine operation.
    // Gateway injects clientCategory from ClientContext before forwarding.
    // Engines: General (default) | Franchisee | Franchisor (+ sub-category fallbacks)
    {
      id: 'SpendDistribution',
      service: 'spendDistribution',
      action: 'recommend',
      label: 'Spend Distribution: Recommend (General)',
      sample: {
        clientCategory: 'General',
        objective: 'traffic',
        businessCategory: 'retail',
        keywords: ['shoes', 'sneakers', 'footwear'],
        geoTargeting: {
          zipCodes: ['92648'],
          radiusMiles: 25
        },
        audience: {
          ageMin: 25,
          ageMax: 44,
          genders: ['MALE', 'FEMALE'],
          interests: ['fashion', 'sports']
        },
        monthlyBudget: 1500,
        channels: ['google', 'meta', 'tiktok']
      }
    },
    {
      id: 'SpendDistributionFranchisee',
      service: 'spendDistribution',
      action: 'recommendFranchisee',
      label: 'Spend Distribution: Recommend (Franchisee)',
      sample: {
        clientCategory: 'Franchisee',
        objective: 'leads',
        businessCategory: 'food',
        keywords: ['pizza', 'delivery', 'takeout'],
        geoTargeting: {
          zipCodes: ['92648', '92649'],
          radiusMiles: 10
        },
        audience: {
          ageMin: 18,
          ageMax: 54,
          genders: ['MALE', 'FEMALE']
        },
        monthlyBudget: 800,
        channels: ['google', 'meta']
      }
    },
    {
      id: 'SpendDistributionFranchisor',
      service: 'spendDistribution',
      action: 'recommendFranchisor',
      label: 'Spend Distribution: Recommend (Franchisor)',
      sample: {
        clientCategory: 'Franchisor',
        objective: 'awareness',
        businessCategory: 'food',
        keywords: ['franchise', 'pizza chain', 'national brand'],
        geoTargeting: {
          zipCodes: ['90210', '10001', '60601'],
          radiusMiles: 50
        },
        audience: {
          ageMin: 30,
          ageMax: 55,
          genders: ['MALE', 'FEMALE'],
          interests: ['business', 'investment', 'entrepreneurship']
        },
        monthlyBudget: 15000,
        channels: ['google', 'meta', 'tiktok']
      }
    }
  ],
  registration: [
    // Health check — hits Registration Function directly (anonymous endpoint)
    {
      id: 'Health',
      service: 'system',
      action: 'health',
      label: 'System: Health Check',
      sample: {},
      endpoint: '/api/health',
      method: 'GET',
      baseUrl: 'https://regapi.positivespend.com'
    },
    // ── Admin ops below route through Management proxy (/api/registration/*).
    // Management validates the Entra JWT, then forwards to Registration Function
    // using its own server-side function key. No client-side key required.
    {
      id: 'GetPending',
      service: 'registration',
      action: 'pending',
      label: 'Registration: List Pending',
      sample: {},
      endpoint: '/api/registration/pending',
      method: 'GET',
      baseUrl: 'https://mgmt.positivespend.com'
    },
    {
      id: 'GetById',
      service: 'registration',
      action: 'get',
      label: 'Registration: Get by ID',
      sample: { registrationId: 'reg-001' },
      endpoint: '/api/registration/{registrationId}',
      method: 'GET',
      baseUrl: 'https://mgmt.positivespend.com'
    },
    {
      id: 'Reject',
      service: 'registration',
      action: 'reject',
      label: 'Registration: Reject Applicant',
      sample: { registrationId: 'reg-001', reason: 'Incomplete information' },
      endpoint: '/api/registration/{registrationId}/reject',
      method: 'POST',
      baseUrl: 'https://mgmt.positivespend.com'
    },
    {
      id: 'Complete',
      service: 'registration',
      action: 'complete',
      label: 'Registration: Approve (Complete)',
      sample: { registrationId: 'reg-001', platformClientId: 'ADP-TestBusiness-0001' },
      endpoint: '/api/registration/{registrationId}/complete',
      method: 'POST',
      baseUrl: 'https://mgmt.positivespend.com'
    },
    // Register — still hits Registration Function directly (CIAM JWT, not staff plane)
    {
      id: 'Register',
      service: 'registration',
      action: 'register',
      label: 'Registration: New Prospect (test)',
      sample: {
        businessName: 'Test Business',
        websiteUrl: 'https://test.com',
        businessCategory: 'retail',
        businessDescription: 'A test registration',
        contactName: 'Test User',
        contactEmail: 'test@example.com',
        contactPhone: '(555) 000-1234'
      },
      endpoint: '/api/registration/register',
      method: 'POST',
      baseUrl: 'https://regapi.positivespend.com'
    }
  ],
  management: [
    {
      id: 'Ping',
      service: 'system',
      action: 'ping',
      label: 'System: Health Check',
      sample: {},
      endpoint: '/health',
      method: 'GET',
      baseUrl: 'https://mgmt.positivespend.com'
    },
    {
      id: 'HelpGet',
      service: 'help',
      action: 'get',
      label: 'Help: Get Content by Key',
      sample: { key: 'client.wizard.budget' },
      endpoint: '/api/help/{key}',
      method: 'GET',
      baseUrl: 'https://mgmt.positivespend.com'
    },
    {
      id: 'DocumentList',
      service: 'documents',
      action: 'list',
      label: 'Documents: List All',
      sample: {},
      endpoint: '/api/documents',
      method: 'GET',
      baseUrl: 'https://mgmt.positivespend.com'
    },
    {
      id: 'DocumentDelete',
      service: 'documents',
      action: 'delete',
      label: 'Documents: Delete by ID',
      sample: { docId: 1 },
      endpoint: '/api/documents/{docId}',
      method: 'DELETE',
      baseUrl: 'https://mgmt.positivespend.com'
    }
  ]
};

export function getServices(providerId) {
  return servicesByProvider[providerId] || [];
}

export function getService(providerId, serviceId) {
  return getServices(providerId).find(s => s.id === serviceId);
}

/**
 * Get unique service modules for a provider
 */
export function getServiceModules(providerId) {
  const services = getServices(providerId);
  const modules = [...new Set(services.map(s => s.service))];
  return modules;
}

/**
 * Get actions for a specific service module
 */
export function getActionsForModule(providerId, serviceModule) {
  return getServices(providerId).filter(s => s.service === serviceModule);
}
