import { NormalizedCampaignInsight } from '../interfaces/campaign-insight.interface';

/**
 * Meta Normalizer Utility
 * أداة توحيد بيانات ميتا
 * 
 * Converts raw Meta Marketing API response into our internal format.
 * يحول استجابة واجهة ميتا للتسويق الخام إلى تنسيقنا الداخلي.
 */
export class MetaNormalizer {
  static normalize(raw: any): NormalizedCampaignInsight {
    const impressions = parseInt(raw.impressions || '0', 10);
    const clicks = parseInt(raw.clicks || '0', 10);
    const spend = parseFloat(raw.spend || '0');

    // Calculate metrics if not provided or to ensure accuracy
    // حساب المقاييس إذا لم تكن موجودة أو لضمان الدقة
    const ctr = impressions > 0 ? (clicks / impressions) * 100 : 0;
    const cpc = clicks > 0 ? spend / clicks : 0;
    const cpm = impressions > 0 ? (spend / impressions) * 1000 : 0;
    const reach = parseInt(raw.reach || '0', 10);
    const frequency = parseFloat(raw.frequency || '1');
    const conversions = parseInt(raw.conversions || '0', 10);
    const costPerResult = parseFloat(raw.cost_per_result || '0');
    const objective = raw.objective || 'N/A';

    return {
      campaignId: raw.campaign_id || 'N/A',
      campaignName: raw.campaign_name || 'Unnamed Campaign',
      impressions,
      clicks,
      spend,
      ctr: parseFloat(ctr.toFixed(4)),
      cpc: parseFloat(cpc.toFixed(4)),
      cpm: parseFloat(cpm.toFixed(4)),
      dateStart: raw.date_start,
      dateStop: raw.date_stop,
      source: 'meta',
      platform: raw.publisher_platform || 'facebook',
      status: raw.effective_status || 'UNKNOWN',
      imageUrl: raw.image_url || raw.thumbnail_url || 'https://images.unsplash.com/photo-1611162617474-5b21e879e113?q=80&w=1000&auto=format&fit=crop', // Real URL or Default Meta placeholder
      adCopy: raw.ad_copy || undefined,
      reach,
      frequency,
      conversions,
      costPerResult,
      objective,
      aiRecommendation: raw.ai_recommendation || raw.aiRecommendation,
    };
  }

  static normalizeList(rawList: any[]): NormalizedCampaignInsight[] {
    return rawList.map((item) => this.normalize(item));
  }
}
