/**
 * Pricing Validator Utility
 *
 * Validates pricing table configuration against the original 5-tier baseline.
 * Used to detect unintended changes to pricing structure, values, or features.
 *
 * Baseline Source: FALLBACK_TIERS array from /app/[lang]/pricing/PricingClient.tsx
 */

// BASELINE PRICING DATA - The immutable "5 we had originally"
export const BASELINE_TIERS = [
  {
    id: 'tier1',
    nameEn: 'Starter',
    nameAr: 'المبتدئ',
    priceGBP: 179,
    setupGBP: 199,
    popular: false,
    featuresEn: [
      'AI Agent for FAQ & Auto-Reply',
      'Automated Appointment Booking',
      'Admin Dashboard',
      'WhatsApp Integration',
      'Basic Analytics',
      'Email Support',
    ],
    featuresAr: [
      'وكيل ذكي للأسئلة الشائعة والردود التلقائية',
      'حجز المواعيد الآلي',
      'لوحة تحكم الإدارة',
      'تكامل واتساب',
      'تحليلات أساسية',
      'دعم البريد الإلكتروني',
    ],
  },
  {
    id: 'tier2',
    nameEn: 'Professional',
    nameAr: 'المحترف',
    priceGBP: 209,
    setupGBP: 199,
    popular: true, // ONLY tier with popular: true
    featuresEn: [
      'Everything in Starter',
      'Send & Receive Quotations',
      'CRM Dashboard',
      'Google & Third-Party Integrations',
      'Deposit Management',
      'No-Show Fee Collection',
      'Appointment Rebooking',
      'Priority Support',
    ],
    featuresAr: [
      'كل مزايا الباقة المبتدئة',
      'إرسال واستقبال عروض الأسعار',
      'لوحة تحكم CRM',
      'تكاملات جوجل وأطراف ثالثة',
      'إدارة المقدمات',
      'تحصيل رسوم عدم الحضور',
      'إعادة حجز المواعيد',
      'دعم ذو أولوية',
    ],
  },
  {
    id: 'tier3',
    nameEn: 'Business',
    nameAr: 'الأعمال',
    priceGBP: 249,
    setupGBP: 199,
    popular: false,
    featuresEn: [
      'Everything in Professional',
      'Multi-Staff Login',
      'Recurring Appointments',
      'Multiple Appointments Setup',
      'AI Voice Receptionist',
      'Call Transfer to Mobile',
      'Advanced Scheduling',
      'Custom Workflows',
    ],
    featuresAr: [
      'كل مزايا الباقة المحترفة',
      'تسجيل دخول متعدد للموظفين',
      'مواعيد متكررة',
      'إعداد مواعيد متعددة',
      'موظفة استقبال صوتية ذكية',
      'تحويل المكالمات للجوال',
      'جدولة متقدمة',
      'سير عمل مخصص',
    ],
  },
  {
    id: 'tier4',
    nameEn: 'Enterprise',
    nameAr: 'المؤسسات',
    priceGBP: 349,
    setupGBP: 199,
    popular: false,
    featuresEn: [
      'Everything in Business',
      'Multi-Inbox Social Management',
      'AI Social Media Assistant',
      'Trend Analysis & Post Ideas',
      'Content Scheduling',
      'Social Media Monitoring',
      'Engagement Analytics',
      'Dedicated Account Manager',
    ],
    featuresAr: [
      'كل مزايا باقة الأعمال',
      'إدارة وسائل التواصل متعددة الصناديق',
      'مساعد وسائل تواصل اجتماعي ذكي',
      'تحليل الاتجاهات وأفكار المنشورات',
      'جدولة المحتوى',
      'مراقبة وسائل التواصل',
      'تحليلات التفاعل',
      'مدير حساب مخصص',
    ],
  },
  {
    id: 'tier5',
    nameEn: 'Ultimate',
    nameAr: 'المتكاملة',
    priceGBP: 449,
    setupGBP: 299, // ONLY tier with setupGBP: 299
    popular: false,
    featuresEn: [
      'Everything in Enterprise',
      'AI Lead Generation',
      'Automated Lead Nurturing',
      'Advanced CRM with Lead Scoring',
      'Multi-Channel Lead Capture',
      'Conversion Optimization',
      'ROI Tracking & Analytics',
      'White-Label Options',
      '24/7 Premium Support',
    ],
    featuresAr: [
      'كل مزايا باقة المؤسسات',
      'توليد العملاء المحتملين بالذكاء الاصطناعي',
      'رعاية العملاء المحتملين الآلية',
      'CRM متقدم مع تقييم العملاء',
      'التقاط العملاء متعدد القنوات',
      'تحسين التحويلات',
      'تتبع وتحليلات عائد الاستثمار',
      'خيارات العلامة البيضاء',
      'دعم متميز على مدار الساعة',
    ],
  },
] as const;

// Type definitions
export interface PricingTier {
  id: string;
  nameEn: string;
  nameAr: string;
  priceGBP: number;
  setupGBP: number;
  popular: boolean;
  featuresEn: string[];
  featuresAr: string[];
  stripeProductId?: string;
  stripePrices?: any[];
}

export interface ValidationError {
  field: string;
  expected: any;
  actual: any;
  tierId?: string;
  severity: 'critical' | 'warning';
}

export interface ValidationReport {
  valid: boolean;
  errors: ValidationError[];
  warnings: ValidationError[];
  summary: string;
  timestamp: string;
}

/**
 * Validates pricing tier configuration against baseline
 */
export function validatePricingTiers(tiers: PricingTier[]): ValidationReport {
  const errors: ValidationError[] = [];
  const warnings: ValidationError[] = [];
  const timestamp = new Date().toISOString();

  // Validation 1: Tier count must be exactly 5
  if (tiers.length !== 5) {
    errors.push({
      field: 'tier_count',
      expected: 5,
      actual: tiers.length,
      severity: 'critical',
    });
  }

  // Validation 2: Verify each tier exists and matches baseline
  const expectedIds = ['tier1', 'tier2', 'tier3', 'tier4', 'tier5'];
  const actualIds = tiers.map(t => t.id);

  // Check for missing tiers
  expectedIds.forEach(expectedId => {
    if (!actualIds.includes(expectedId)) {
      errors.push({
        field: 'tier_id',
        expected: expectedId,
        actual: 'missing',
        severity: 'critical',
      });
    }
  });

  // Check for unexpected tiers
  actualIds.forEach(actualId => {
    if (!expectedIds.includes(actualId)) {
      errors.push({
        field: 'tier_id',
        expected: 'none',
        actual: actualId,
        severity: 'critical',
      });
    }
  });

  // Validation 3: Validate each tier's detailed configuration
  BASELINE_TIERS.forEach((baseline) => {
    const actual = tiers.find(t => t.id === baseline.id);

    if (!actual) {
      // Already caught in tier existence check
      return;
    }

    // Price validation
    if (actual.priceGBP !== baseline.priceGBP) {
      errors.push({
        field: 'priceGBP',
        expected: baseline.priceGBP,
        actual: actual.priceGBP,
        tierId: baseline.id,
        severity: 'critical',
      });
    }

    // Setup fee validation
    if (actual.setupGBP !== baseline.setupGBP) {
      errors.push({
        field: 'setupGBP',
        expected: baseline.setupGBP,
        actual: actual.setupGBP,
        tierId: baseline.id,
        severity: 'critical',
      });
    }

    // Popular flag validation
    if (actual.popular !== baseline.popular) {
      errors.push({
        field: 'popular',
        expected: baseline.popular,
        actual: actual.popular,
        tierId: baseline.id,
        severity: 'critical',
      });
    }

    // Tier name validation (English)
    if (actual.nameEn !== baseline.nameEn) {
      errors.push({
        field: 'nameEn',
        expected: baseline.nameEn,
        actual: actual.nameEn,
        tierId: baseline.id,
        severity: 'critical',
      });
    }

    // Tier name validation (Arabic)
    if (actual.nameAr !== baseline.nameAr) {
      errors.push({
        field: 'nameAr',
        expected: baseline.nameAr,
        actual: actual.nameAr,
        tierId: baseline.id,
        severity: 'critical',
      });
    }

    // Feature list validation (English)
    if (JSON.stringify(actual.featuresEn) !== JSON.stringify(baseline.featuresEn)) {
      warnings.push({
        field: 'featuresEn',
        expected: baseline.featuresEn,
        actual: actual.featuresEn,
        tierId: baseline.id,
        severity: 'warning',
      });
    }

    // Feature list validation (Arabic)
    if (JSON.stringify(actual.featuresAr) !== JSON.stringify(baseline.featuresAr)) {
      warnings.push({
        field: 'featuresAr',
        expected: baseline.featuresAr,
        actual: actual.featuresAr,
        tierId: baseline.id,
        severity: 'warning',
      });
    }
  });

  // Validation 4: Ensure exactly one popular tier (tier2)
  const popularTiers = tiers.filter(t => t.popular);
  if (popularTiers.length !== 1) {
    errors.push({
      field: 'popular_count',
      expected: 1,
      actual: popularTiers.length,
      severity: 'critical',
    });
  } else if (popularTiers[0].id !== 'tier2') {
    errors.push({
      field: 'popular_tier',
      expected: 'tier2',
      actual: popularTiers[0].id,
      severity: 'critical',
    });
  }

  // Generate summary
  const valid = errors.length === 0 && warnings.length === 0;
  let summary = '';

  if (valid) {
    summary = '✅ All pricing tiers match baseline configuration. No changes detected.';
  } else {
    const criticalCount = errors.length;
    const warningCount = warnings.length;
    summary = `❌ Validation failed: ${criticalCount} critical error(s), ${warningCount} warning(s)`;
  }

  return {
    valid,
    errors,
    warnings,
    summary,
    timestamp,
  };
}

/**
 * Validates specific currency conversion logic
 */
export function validateCurrencyConversion(
  priceGBP: number,
  currency: string,
  expectedRate: number,
  actualConvertedPrice: number
): boolean {
  const expectedPrice = Math.round(priceGBP * expectedRate);
  return actualConvertedPrice === expectedPrice;
}

/**
 * Validates yearly discount calculation (7% discount)
 */
export function validateYearlyDiscount(
  priceGBP: number,
  actualDiscountedPrice: number
): boolean {
  const expectedPrice = priceGBP * 0.93; // 7% discount
  return Math.abs(actualDiscountedPrice - expectedPrice) < 0.01; // Allow floating point tolerance
}

/**
 * Pretty-prints validation report for console output
 */
export function formatValidationReport(report: ValidationReport): string {
  let output = `\n${'='.repeat(60)}\n`;
  output += `PRICING VALIDATION REPORT\n`;
  output += `Timestamp: ${report.timestamp}\n`;
  output += `${'='.repeat(60)}\n\n`;
  output += `${report.summary}\n\n`;

  if (report.errors.length > 0) {
    output += `🚨 CRITICAL ERRORS (${report.errors.length}):\n`;
    output += `${'-'.repeat(60)}\n`;
    report.errors.forEach((error, idx) => {
      output += `${idx + 1}. ${error.tierId || 'GLOBAL'} - ${error.field}\n`;
      output += `   Expected: ${JSON.stringify(error.expected)}\n`;
      output += `   Actual:   ${JSON.stringify(error.actual)}\n\n`;
    });
  }

  if (report.warnings.length > 0) {
    output += `⚠️  WARNINGS (${report.warnings.length}):\n`;
    output += `${'-'.repeat(60)}\n`;
    report.warnings.forEach((warning, idx) => {
      output += `${idx + 1}. ${warning.tierId || 'GLOBAL'} - ${warning.field}\n`;
      output += `   Expected: ${JSON.stringify(warning.expected).substring(0, 100)}...\n`;
      output += `   Actual:   ${JSON.stringify(warning.actual).substring(0, 100)}...\n\n`;
    });
  }

  output += `${'='.repeat(60)}\n`;
  return output;
}

/**
 * Quick validation check - returns boolean only
 */
export function isPricingValid(tiers: PricingTier[]): boolean {
  const report = validatePricingTiers(tiers);
  return report.valid;
}

/**
 * Validates tier at specific index matches baseline
 */
export function validateTierAtIndex(tier: PricingTier, index: number): ValidationError[] {
  const errors: ValidationError[] = [];
  const baseline = BASELINE_TIERS[index];

  if (!baseline) {
    errors.push({
      field: 'tier_index',
      expected: `index ${index} to exist in baseline`,
      actual: 'out of range',
      severity: 'critical',
    });
    return errors;
  }

  if (tier.id !== baseline.id) {
    errors.push({
      field: 'id',
      expected: baseline.id,
      actual: tier.id,
      tierId: baseline.id,
      severity: 'critical',
    });
  }

  if (tier.priceGBP !== baseline.priceGBP) {
    errors.push({
      field: 'priceGBP',
      expected: baseline.priceGBP,
      actual: tier.priceGBP,
      tierId: baseline.id,
      severity: 'critical',
    });
  }

  if (tier.setupGBP !== baseline.setupGBP) {
    errors.push({
      field: 'setupGBP',
      expected: baseline.setupGBP,
      actual: tier.setupGBP,
      tierId: baseline.id,
      severity: 'critical',
    });
  }

  return errors;
}

/**
 * Export baseline tier IDs for test assertions
 */
export const BASELINE_TIER_IDS = ['tier1', 'tier2', 'tier3', 'tier4', 'tier5'] as const;

/**
 * Export baseline pricing values for test assertions
 */
export const BASELINE_PRICES = {
  tier1: 179,
  tier2: 209,
  tier3: 249,
  tier4: 349,
  tier5: 449,
} as const;

/**
 * Export baseline setup fees for test assertions
 */
export const BASELINE_SETUP_FEES = {
  tier1: 199,
  tier2: 199,
  tier3: 199,
  tier4: 199,
  tier5: 299,
} as const;

/**
 * Export popular tier ID
 */
export const POPULAR_TIER_ID = 'tier2' as const;
