/**
 * [MOCK-MARKETING-INTEGRATION] Omnichannel Marketing DataSource
 */

export interface MarketingChannel {
  id: string;
  name: string;
  type: 'email' | 'social' | 'sms' | 'push' | 'ads';
  config: Record<string, any>;
  status: 'active' | 'inactive';
}

export interface MarketingCampaign {
  id: string;
  name: string;
  channels: string[];
  targetAudience: Record<string, any>;
  content: Record<string, any>;
  schedule?: string;
  status: 'draft' | 'scheduled' | 'running' | 'completed' | 'paused';
  metrics?: CampaignMetrics;
}

export interface CampaignMetrics {
  impressions: number;
  clicks: number;
  conversions: number;
  revenue: number;
  cost: number;
}

export interface AutomationRule {
  id: string;
  name: string;
  trigger: {
    type: 'user_action' | 'time_based' | 'event';
    conditions: Record<string, any>;
  };
  actions: Array<{
    type: string;
    config: Record<string, any>;
  }>;
  status: 'active' | 'inactive';
}

export interface ABTestResult {
  winner: string;
  results: Record<string, any>;
}

export interface IOmnichannelMarketingDataSource {
  integrateChannels(channels: Array<{ name: string; type: string; config: Record<string, any> }>): Promise<MarketingChannel[]>;
  createAutomation(rule: Omit<AutomationRule, 'id'>): Promise<AutomationRule>;
  analyzeCampaign(campaignId: string, timeRange: { start: string; end: string }): Promise<CampaignMetrics>;
  runABTest(params: { name: string; variants: Array<{ id: string; content: Record<string, any> }>; trafficSplit: number[] }): Promise<ABTestResult>;
}

class MockOmnichannelMarketingDataSource implements IOmnichannelMarketingDataSource {
  async integrateChannels(channels: Array<{ name: string; type: string; config: Record<string, any> }>): Promise<MarketingChannel[]> {
    return channels.map((ch, i) => ({
      id: `ch_${Date.now()}_${i}`,
      name: ch.name,
      type: ch.type as MarketingChannel['type'],
      config: ch.config,
      status: 'active' as const,
    }));
  }

  async createAutomation(rule: Omit<AutomationRule, 'id'>): Promise<AutomationRule> {
    return { ...rule, id: `rule_${Date.now()}` };
  }

  async analyzeCampaign(campaignId: string, timeRange: { start: string; end: string }): Promise<CampaignMetrics> {
    return {
      impressions: 10000,
      clicks: 500,
      conversions: 50,
      revenue: 5000,
      cost: 500,
    };
  }

  async runABTest(params: { name: string; variants: Array<{ id: string; content: Record<string, any> }>; trafficSplit: number[] }): Promise<ABTestResult> {
    return {
      winner: params.variants[0].id,
      results: {
        [params.variants[0].id]: { impressions: 500, conversions: 25, conversionRate: 0.05 },
        [params.variants[1]?.id || 'variant_b']: { impressions: 500, conversions: 20, conversionRate: 0.04 },
      },
    };
  }
}

class ApiOmnichannelMarketingDataSource implements IOmnichannelMarketingDataSource {
  private baseUrl = '/api/omnichannel';

  async integrateChannels(channels: Array<{ name: string; type: string; config: Record<string, any> }>): Promise<MarketingChannel[]> {
    const res = await fetch(`${this.baseUrl}/marketing/channels`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ channels }),
    });
    const data = await res.json();
    return data.data;
  }

  async createAutomation(rule: Omit<AutomationRule, 'id'>): Promise<AutomationRule> {
    const res = await fetch(`${this.baseUrl}/marketing/automation`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(rule),
    });
    const data = await res.json();
    return data.data;
  }

  async analyzeCampaign(campaignId: string, timeRange: { start: string; end: string }): Promise<CampaignMetrics> {
    const res = await fetch(`${this.baseUrl}/marketing/campaign/${campaignId}/analyze?start=${timeRange.start}&end=${timeRange.end}`);
    const data = await res.json();
    return data.data;
  }

  async runABTest(params: { name: string; variants: Array<{ id: string; content: Record<string, any> }>; trafficSplit: number[] }): Promise<ABTestResult> {
    const res = await fetch(`${this.baseUrl}/marketing/ab-test`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(params),
    });
    const data = await res.json();
    return data.data;
  }
}

const useMock = process.env.REACT_APP_USE_MOCK === 'true';
export const omnichannelMarketingDataSource: IOmnichannelMarketingDataSource = useMock
  ? new MockOmnichannelMarketingDataSource()
  : new ApiOmnichannelMarketingDataSource();
