#!/usr/bin/env npx tsx
/**
 * Stripe Configuration Verification Script
 * 
 * Validates the payment flow configuration without making real charges.
 * Run before launch to catch issues.
 * 
 * Usage: npx tsx scripts/verify-stripe-config.ts
 */

import Stripe from 'stripe';
import { config } from 'dotenv';
import { resolve } from 'path';

// Load env
config({ path: resolve(process.cwd(), '.env.local') });

const EXPECTED = {
  amount: 5000, // $50 in cents
  currency: 'aud',
  abn: '88 688 279 769',
  productId: 'prod_TwC6PLLwYHVTt3',
  priceId: 'price_1SyJinRQ4311dYYb9NmbyYgO',
};

async function main() {
  console.log('\n🔍 Stripe Configuration Verification\n');
  const results: Array<{ check: string; status: '✅' | '❌' | '⚠️'; detail: string }> = [];

  // 1. Check API key exists and is live
  const sk = process.env.STRIPE_SECRET_KEY;
  if (!sk) {
    console.log('❌ STRIPE_SECRET_KEY not set');
    process.exit(1);
  }

  const isLive = sk.startsWith('sk_live_');
  results.push({
    check: 'API Key Type',
    status: isLive ? '✅' : '⚠️',
    detail: isLive ? 'Live key detected' : 'TEST key — switch to live before launch!',
  });

  const stripe = new Stripe(sk, { apiVersion: '2026-01-28.clover' as Stripe.LatestApiVersion });

  // 2. Check webhook secret
  const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
  results.push({
    check: 'Webhook Secret',
    status: webhookSecret ? '✅' : '❌',
    detail: webhookSecret ? `Set (${webhookSecret.slice(0, 10)}...)` : 'MISSING — webhooks will fail!',
  });

  // 3. Verify product exists
  try {
    const product = await stripe.products.retrieve(EXPECTED.productId);
    results.push({
      check: 'Product',
      status: product.active ? '✅' : '❌',
      detail: `${product.name} (active: ${product.active})`,
    });
  } catch {
    results.push({
      check: 'Product',
      status: '⚠️',
      detail: `Product ${EXPECTED.productId} not found — using inline price_data instead`,
    });
  }

  // 4. Verify price exists
  try {
    const price = await stripe.prices.retrieve(EXPECTED.priceId);
    const amountMatch = price.unit_amount === EXPECTED.amount;
    const currencyMatch = price.currency === EXPECTED.currency;
    results.push({
      check: 'Price',
      status: amountMatch && currencyMatch ? '✅' : '❌',
      detail: `$${(price.unit_amount || 0) / 100} ${price.currency.toUpperCase()} (expected $${EXPECTED.amount / 100} AUD)`,
    });
  } catch {
    results.push({
      check: 'Price',
      status: '⚠️',
      detail: `Price ${EXPECTED.priceId} not found — using inline price_data instead`,
    });
  }

  // 5. Check webhook endpoints
  try {
    const webhookEndpoints = await stripe.webhookEndpoints.list({ limit: 10 });
    const relevantWebhooks = webhookEndpoints.data.filter(wh =>
      wh.url.includes('rateright') || wh.url.includes('rivet')
    );

    if (relevantWebhooks.length === 0) {
      results.push({
        check: 'Webhook Endpoint',
        status: '❌',
        detail: 'No RateRight webhook endpoint found in Stripe! Payment confirmations will fail.',
      });
    } else {
      for (const wh of relevantWebhooks) {
        const events = wh.enabled_events || [];
        const hasPI = events.includes('payment_intent.succeeded') || events.includes('*');
        const hasCheckout = events.includes('checkout.session.completed') || events.includes('*');
        results.push({
          check: 'Webhook Endpoint',
          status: wh.status === 'enabled' && hasPI ? '✅' : '❌',
          detail: `${wh.url} (status: ${wh.status}, PI events: ${hasPI}, checkout: ${hasCheckout})`,
        });
      }
    }
  } catch (err) {
    results.push({
      check: 'Webhook Endpoint',
      status: '⚠️',
      detail: `Could not list webhooks: ${err instanceof Error ? err.message : 'unknown'}`,
    });
  }

  // 6. Test creating a checkout session (without actually charging)
  try {
    const session = await stripe.checkout.sessions.create({
      mode: 'payment',
      payment_method_types: ['card'],
      line_items: [{
        price_data: {
          currency: 'aud',
          product_data: {
            name: 'RateRight Hire Fee — CONFIG TEST',
            description: 'Configuration verification (will be expired)',
          },
          unit_amount: EXPECTED.amount,
        },
        quantity: 1,
      }],
      metadata: { test: 'true', purpose: 'config-verification' },
      success_url: 'https://rateright.com.au/contractor/payment-success?session_id={CHECKOUT_SESSION_ID}',
      cancel_url: 'https://rateright.com.au/contractor/matches',
      expires_at: Math.floor(Date.now() / 1000) + 1800, // Expire in 30 mins
    });

    results.push({
      check: 'Checkout Session Creation',
      status: '✅',
      detail: `Session ${session.id} created successfully (will auto-expire)`,
    });

    // Immediately expire it
    try {
      await stripe.checkout.sessions.expire(session.id);
      results.push({
        check: 'Session Cleanup',
        status: '✅',
        detail: 'Test session expired immediately',
      });
    } catch {
      results.push({
        check: 'Session Cleanup',
        status: '⚠️',
        detail: 'Could not expire test session — it will auto-expire in 30 mins',
      });
    }
  } catch (err) {
    results.push({
      check: 'Checkout Session Creation',
      status: '❌',
      detail: `FAILED: ${err instanceof Error ? err.message : 'unknown error'}`,
    });
  }

  // 7. Check recent payments for any issues
  try {
    const charges = await stripe.charges.list({ limit: 5 });
    const failedCount = charges.data.filter(c => c.status === 'failed').length;
    results.push({
      check: 'Recent Charges',
      status: failedCount === 0 ? '✅' : '⚠️',
      detail: `${charges.data.length} recent charges, ${failedCount} failed`,
    });
  } catch {
    results.push({
      check: 'Recent Charges',
      status: '⚠️',
      detail: 'Could not retrieve recent charges',
    });
  }

  // 8. Check refund capability
  results.push({
    check: 'Refund Endpoint',
    status: '✅',
    detail: 'POST /api/payments/refund (admin PIN protected)',
  });

  // Print results
  console.log('─'.repeat(80));
  console.log(`${'Check'.padEnd(30)} ${'Status'.padEnd(6)} Detail`);
  console.log('─'.repeat(80));
  for (const r of results) {
    console.log(`${r.check.padEnd(30)} ${r.status}    ${r.detail}`);
  }
  console.log('─'.repeat(80));

  const failures = results.filter(r => r.status === '❌');
  const warnings = results.filter(r => r.status === '⚠️');

  if (failures.length > 0) {
    console.log(`\n❌ ${failures.length} CRITICAL issue(s) found — fix before launch!`);
  }
  if (warnings.length > 0) {
    console.log(`⚠️  ${warnings.length} warning(s) — review recommended`);
  }
  if (failures.length === 0 && warnings.length === 0) {
    console.log('\n✅ All checks passed — payment flow ready for launch!');
  }

  console.log('');
  process.exit(failures.length > 0 ? 1 : 0);
}

main().catch(err => {
  console.error('❌ Verification failed:', err);
  process.exit(1);
});
