/**
 * Attribution Service
 *
 * Marketing attribution tracking for the staff dashboard.
 * Tracks source attribution for demos, conversions, and revenue.
 */

import type {
  Attribution,
  AttributionFilters,
  SourceAttribution,
  BlogAttribution,
  AttributionSource,
  AttributionModel,
} from '@/lib/types/experiments.types';

// ============================================================================
// Attribution Calculation
// ============================================================================

/**
 * Get attribution data with filters
 */
export async function getAttribution(
  filters: AttributionFilters = {}
): Promise<Attribution> {
  const now = new Date();
  const thirtyDaysAgo = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);

  const startDate = filters.startDate ? new Date(filters.startDate) : thirtyDaysAgo;
  const endDate = filters.endDate ? new Date(filters.endDate) : now;
  const model: AttributionModel = filters.model || 'last_touch';

  // In production, this would query the database for actual attribution data
  // For now, using realistic mock data
  const sources: SourceAttribution[] = [
    {
      source: 'organic',
      visitors: 12450,
      demos: 312,
      conversions: 89,
      revenue: 178000,
      conversionRate: 28.5,
      costPerAcquisition: 0,
    },
    {
      source: 'paid',
      visitors: 8920,
      demos: 267,
      conversions: 72,
      revenue: 144000,
      conversionRate: 26.9,
      costPerAcquisition: 125,
    },
    {
      source: 'blog',
      visitors: 6780,
      demos: 203,
      conversions: 61,
      revenue: 122000,
      conversionRate: 30.0,
      costPerAcquisition: 15,
    },
    {
      source: 'referral',
      visitors: 3240,
      demos: 129,
      conversions: 52,
      revenue: 104000,
      conversionRate: 40.3,
      costPerAcquisition: 0,
    },
    {
      source: 'direct',
      visitors: 4560,
      demos: 137,
      conversions: 38,
      revenue: 76000,
      conversionRate: 27.7,
      costPerAcquisition: 0,
    },
    {
      source: 'social',
      visitors: 2890,
      demos: 87,
      conversions: 19,
      revenue: 38000,
      conversionRate: 21.8,
      costPerAcquisition: 45,
    },
    {
      source: 'email',
      visitors: 1850,
      demos: 74,
      conversions: 28,
      revenue: 56000,
      conversionRate: 37.8,
      costPerAcquisition: 8,
    },
  ];

  // Filter sources if specified
  const filteredSources = filters.sources && filters.sources.length > 0
    ? sources.filter((s) => filters.sources!.includes(s.source))
    : sources;

  const blogAttribution: BlogAttribution[] = [
    {
      postSlug: 'whatsapp-business-api-guide-2024',
      postTitle: 'Complete WhatsApp Business API Guide 2024',
      views: 8450,
      demos: 67,
      conversions: 23,
      revenue: 46000,
      conversionRate: 34.3,
    },
    {
      postSlug: 'appointment-scheduling-best-practices',
      postTitle: 'Appointment Scheduling Best Practices for Medical Clinics',
      views: 6320,
      demos: 51,
      conversions: 18,
      revenue: 36000,
      conversionRate: 35.3,
    },
    {
      postSlug: 'healthcare-communication-gcc',
      postTitle: 'Healthcare Communication in the GCC: A Complete Guide',
      views: 5890,
      demos: 44,
      conversions: 14,
      revenue: 28000,
      conversionRate: 31.8,
    },
    {
      postSlug: 'reduce-no-shows-whatsapp-reminders',
      postTitle: 'How to Reduce No-Shows with WhatsApp Reminders',
      views: 4210,
      demos: 38,
      conversions: 11,
      revenue: 22000,
      conversionRate: 28.9,
    },
    {
      postSlug: 'patient-engagement-automation',
      postTitle: 'Patient Engagement Automation: ROI Calculator',
      views: 3780,
      demos: 29,
      conversions: 9,
      revenue: 18000,
      conversionRate: 31.0,
    },
  ];

  const topConvertingContent = [
    {
      url: '/pricing',
      title: 'Pricing Page',
      conversionRate: 8.5,
      revenue: 245000,
      conversions: 122,
    },
    {
      url: '/features/appointment-reminders',
      title: 'Appointment Reminders Feature',
      conversionRate: 6.2,
      revenue: 89000,
      conversions: 44,
    },
    {
      url: '/demo',
      title: 'Book a Demo',
      conversionRate: 5.8,
      revenue: 78000,
      conversions: 39,
    },
    {
      url: '/industries/healthcare',
      title: 'Healthcare Solutions',
      conversionRate: 5.1,
      revenue: 67000,
      conversions: 33,
    },
    {
      url: '/case-studies/medclinic-dubai',
      title: 'MedClinic Dubai Case Study',
      conversionRate: 4.7,
      revenue: 54000,
      conversions: 27,
    },
  ];

  // Calculate totals
  const totals = {
    visitors: filteredSources.reduce((sum, s) => sum + s.visitors, 0),
    demos: filteredSources.reduce((sum, s) => sum + s.demos, 0),
    conversions: filteredSources.reduce((sum, s) => sum + s.conversions, 0),
    revenue: filteredSources.reduce((sum, s) => sum + s.revenue, 0),
    overallConversionRate: 0,
  };
  totals.overallConversionRate =
    totals.demos > 0
      ? Math.round((totals.conversions / totals.demos) * 1000) / 10
      : 0;

  return {
    period: {
      start: startDate.toISOString(),
      end: endDate.toISOString(),
    },
    model,
    sources: filteredSources,
    blogAttribution,
    topConvertingContent,
    totals,
  };
}

/**
 * Get attribution summary for a quick overview
 */
export async function getAttributionSummary(): Promise<{
  topSource: AttributionSource;
  topSourceRevenue: number;
  totalRevenue: number;
  avgConversionRate: number;
  blogDemos: number;
  blogConversionRate: number;
}> {
  const attribution = await getAttribution();

  // Find top source by revenue
  const topSourceData = attribution.sources.reduce((top, current) =>
    current.revenue > top.revenue ? current : top
  );

  // Calculate blog metrics
  const blogDemos = attribution.blogAttribution.reduce((sum, b) => sum + b.demos, 0);
  const blogConversions = attribution.blogAttribution.reduce((sum, b) => sum + b.conversions, 0);
  const blogConversionRate = blogDemos > 0 ? (blogConversions / blogDemos) * 100 : 0;

  return {
    topSource: topSourceData.source,
    topSourceRevenue: topSourceData.revenue,
    totalRevenue: attribution.totals.revenue,
    avgConversionRate: attribution.totals.overallConversionRate,
    blogDemos,
    blogConversionRate: Math.round(blogConversionRate * 10) / 10,
  };
}

/**
 * Get revenue breakdown by source
 */
export async function getRevenueBySource(): Promise<
  Array<{ source: AttributionSource; revenue: number; percentage: number }>
> {
  const attribution = await getAttribution();
  const totalRevenue = attribution.totals.revenue;

  return attribution.sources.map((s) => ({
    source: s.source,
    revenue: s.revenue,
    percentage: totalRevenue > 0 ? Math.round((s.revenue / totalRevenue) * 1000) / 10 : 0,
  }));
}

/**
 * Compare attribution between two periods
 */
export async function compareAttributionPeriods(
  currentStart: string,
  currentEnd: string,
  previousStart: string,
  previousEnd: string
): Promise<{
  current: Attribution;
  previous: Attribution;
  changes: {
    visitorsChange: number;
    demosChange: number;
    conversionsChange: number;
    revenueChange: number;
    conversionRateChange: number;
  };
}> {
  const current = await getAttribution({ startDate: currentStart, endDate: currentEnd });
  const previous = await getAttribution({ startDate: previousStart, endDate: previousEnd });

  const calcChange = (curr: number, prev: number): number => {
    if (prev === 0) return curr > 0 ? 100 : 0;
    return Math.round(((curr - prev) / prev) * 1000) / 10;
  };

  return {
    current,
    previous,
    changes: {
      visitorsChange: calcChange(current.totals.visitors, previous.totals.visitors),
      demosChange: calcChange(current.totals.demos, previous.totals.demos),
      conversionsChange: calcChange(current.totals.conversions, previous.totals.conversions),
      revenueChange: calcChange(current.totals.revenue, previous.totals.revenue),
      conversionRateChange: calcChange(
        current.totals.overallConversionRate,
        previous.totals.overallConversionRate
      ),
    },
  };
}
