#!/usr/bin/env node

/**
 * Update Stripe Yearly Prices to Correct 7% Discount
 *
 * This script creates NEW yearly prices with the correct formula:
 * Yearly Total = Monthly Price × 12 × 0.93 (7% discount)
 *
 * Since Stripe prices cannot be modified once created, this script:
 * 1. Reads current product IDs from stripe-prices.json
 * 2. Creates NEW yearly prices with correct amounts
 * 3. Archives the OLD yearly prices
 * 4. Updates stripe-prices.json with new price IDs
 *
 * Run with: node scripts/update-stripe-yearly-prices.js
 */

const Stripe = require('stripe');
const fs = require('fs');
const path = require('path');

// Initialize Stripe
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

// 7% yearly discount (matching PRICING_CONFIG.YEARLY_DISCOUNT_PERCENT)
const YEARLY_DISCOUNT_PERCENT = 7;
const YEARLY_DISCOUNT_MULTIPLIER = 1 - (YEARLY_DISCOUNT_PERCENT / 100); // 0.93

// GBP to QAR exchange rate (matching CurrencyManager rates)
const GBP_TO_QAR_RATE = 4.62;

/**
 * Convert GBP to QAR cents
 * @param gbpAmount - Amount in GBP
 * @returns Amount in QAR cents (rounded)
 */
function gbpToQarCents(gbpAmount) {
  return Math.round(gbpAmount * GBP_TO_QAR_RATE * 100);
}

// Tier monthly prices in GBP (from pricing-tiers.ts)
// These get converted to QAR for Stripe
const TIER_PRICES_GBP = {
  tier1: 179,  // £179/month → 827 QAR/month
  tier2: 209,  // £209/month → 966 QAR/month
  tier3: 249,  // £249/month → 1,150 QAR/month
  tier4: 349,  // £349/month → 1,612 QAR/month
  tier5: 449,  // £449/month → 2,074 QAR/month
};

/**
 * Calculate the correct yearly total with 7% discount
 * @param monthlyPriceCents - Monthly price in cents (QAR)
 * @returns Yearly total in cents
 */
function calculateYearlyTotalCents(monthlyPriceCents) {
  return Math.round(monthlyPriceCents * 12 * YEARLY_DISCOUNT_MULTIPLIER);
}

async function updateYearlyPrices() {
  console.log('\n🔄 Updating Stripe Yearly Prices to Correct 7% Discount\n');
  console.log(`💱 Exchange Rate: 1 GBP = ${GBP_TO_QAR_RATE} QAR`);
  console.log(`📉 Yearly Discount: ${YEARLY_DISCOUNT_PERCENT}%`);
  console.log(`   Multiplier: ${YEARLY_DISCOUNT_MULTIPLIER}\n`);

  // Read current stripe-prices.json
  const configPath = path.join(__dirname, '../lib/config/stripe-prices.json');
  let currentConfig;

  try {
    currentConfig = JSON.parse(fs.readFileSync(configPath, 'utf8'));
    console.log('📖 Loaded current stripe-prices.json\n');
  } catch (error) {
    console.error('❌ Could not read stripe-prices.json:', error.message);
    process.exit(1);
  }

  // Display current vs correct prices
  console.log('📊 Price Comparison:\n');
  console.log('Tier     | GBP/mo | QAR/mo  | Correct Yearly | Formula');
  console.log('---------|--------|---------|----------------|--------------------------------');

  for (const [tierId, priceGBP] of Object.entries(TIER_PRICES_GBP)) {
    const monthlyQarCents = gbpToQarCents(priceGBP);
    const correctYearly = calculateYearlyTotalCents(monthlyQarCents);
    const monthlyQAR = (monthlyQarCents / 100).toFixed(0);
    const yearlyQAR = (correctYearly / 100).toFixed(2);
    const formula = `${monthlyQAR} × 12 × 0.93`;

    console.log(`${tierId}    | £${priceGBP.toString().padStart(3)}   | ${monthlyQAR.padStart(5)} QAR | ${yearlyQAR.padStart(10)} QAR | ${formula}`);
  }

  console.log('\n');

  // Confirm before proceeding
  const readline = require('readline');
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

  const answer = await new Promise((resolve) => {
    rl.question('⚠️  Create new yearly prices with these amounts? (yes/no): ', resolve);
  });
  rl.close();

  if (answer.toLowerCase() !== 'yes') {
    console.log('\n❌ Cancelled. No changes made.\n');
    process.exit(0);
  }

  console.log('\n🏗️  Creating new yearly prices...\n');

  const updatedTiers = {};

  for (const [tierId, priceGBP] of Object.entries(TIER_PRICES_GBP)) {
    const tierConfig = currentConfig.tiers[tierId];

    if (!tierConfig) {
      console.log(`⚠️  ${tierId}: No config found, skipping`);
      continue;
    }

    const productId = tierConfig.productId;
    const oldYearlyPriceId = tierConfig.yearly;

    // Convert GBP to QAR cents
    const monthlyQarCents = gbpToQarCents(priceGBP);
    const correctYearlyTotal = calculateYearlyTotalCents(monthlyQarCents);
    const monthlyEquivalent = Math.round(correctYearlyTotal / 12);

    console.log(`📦 ${tierId}: £${priceGBP}/month → ${monthlyQarCents / 100} QAR/month`);

    try {
      // Create new yearly price with correct amount
      const newYearlyPrice = await stripe.prices.create({
        product: productId,
        unit_amount: correctYearlyTotal,
        currency: 'qar',
        recurring: {
          interval: 'year',
          interval_count: 1,
          trial_period_days: 14,
        },
        metadata: {
          tier_id: tierId,
          billing_period: 'yearly',
          monthly_equivalent_qar: monthlyEquivalent.toString(),
          yearly_discount_percent: YEARLY_DISCOUNT_PERCENT.toString(),
          price_gbp: priceGBP.toString(),
          corrected_from: oldYearlyPriceId,
        },
      });

      console.log(`   ✅ Created new yearly price ${newYearlyPrice.id}`);
      console.log(`   📅 ${(correctYearlyTotal / 100).toFixed(2)} QAR/year (${(monthlyEquivalent / 100).toFixed(0)} QAR/month equivalent)`);
      console.log(`   💵 Saves ${((monthlyQarCents * 12) - correctYearlyTotal) / 100} QAR/year (7%)`);

      // Archive old price (set to inactive)
      if (oldYearlyPriceId) {
        try {
          await stripe.prices.update(oldYearlyPriceId, { active: false });
          console.log(`   📦 Archived old price: ${oldYearlyPriceId}`);
        } catch (archiveError) {
          console.log(`   ⚠️  Could not archive old price: ${archiveError.message}`);
        }
      }

      // Store updated config
      updatedTiers[tierId] = {
        productId: productId,
        monthly: tierConfig.monthly,
        yearly: newYearlyPrice.id,
      };

      console.log('');

    } catch (error) {
      console.error(`❌ ${tierId}: Error creating price:`, error.message);
      // Keep old config for this tier
      updatedTiers[tierId] = tierConfig;
    }
  }

  // Update stripe-prices.json
  const newConfig = {
    ...currentConfig,
    tiers: updatedTiers,
    lastUpdated: new Date().toISOString(),
    yearlyDiscountPercent: YEARLY_DISCOUNT_PERCENT,
  };

  // Backup old config
  const backupPath = configPath.replace('.json', `.backup-${Date.now()}.json`);
  fs.writeFileSync(backupPath, JSON.stringify(currentConfig, null, 2));
  console.log(`📦 Backed up old config to: ${backupPath}\n`);

  // Write new config
  fs.writeFileSync(configPath, JSON.stringify(newConfig, null, 2));
  console.log(`✅ Updated stripe-prices.json\n`);

  // Summary
  console.log('🎉 Done! Summary:\n');
  console.log('Tier     | New Yearly Price ID');
  console.log('---------|--------------------');
  for (const [tierId, config] of Object.entries(updatedTiers)) {
    console.log(`${tierId}    | ${config.yearly}`);
  }

  console.log('\n📝 Next steps:');
  console.log('1. Verify the new prices in Stripe Dashboard');
  console.log('2. Test a yearly checkout flow');
  console.log('3. Commit the updated stripe-prices.json\n');
}

// Check for required environment variable
if (!process.env.STRIPE_SECRET_KEY) {
  console.error('❌ STRIPE_SECRET_KEY environment variable is required');
  console.log('\nUsage: STRIPE_SECRET_KEY=sk_xxx node scripts/update-stripe-yearly-prices.js\n');
  process.exit(1);
}

updateYearlyPrices().catch((error) => {
  console.error('\n❌ Fatal error:', error);
  process.exit(1);
});
