/**
 * Local test script for the Payout Retry Processor Lambda.
 *
 * Usage:
 *   cd lambdas/payoutRetryProcessor
 *   npm run local
 */

// Import the handler
const { handler } = require("./index");

async function runTest() {
  console.log("===========================================");
  console.log("  Payout Retry Processor - Local Test");
  console.log("===========================================\n");

  console.log("Environment:");
  console.log(`  DATABASE_URL: ${process.env.DATABASE_URL ? "***configured***" : "NOT SET"}`);
  console.log(`  STRIPE_SECRET_KEY: ${process.env.STRIPE_SECRET_KEY?.startsWith("sk_test") ? "test mode" : process.env.STRIPE_SECRET_KEY ? "LIVE MODE!" : "NOT SET"}`);
  console.log(`  EMAIL_ENABLED: ${process.env.EMAIL_ENABLED}`);
  console.log("");

  // Warn if using live Stripe key
  if (process.env.STRIPE_SECRET_KEY && !process.env.STRIPE_SECRET_KEY.startsWith("sk_test")) {
    console.log("\n⚠️  WARNING: You are using a LIVE Stripe key!");
    console.log("    Real transfers will be created. Press Ctrl+C to abort.\n");
    await new Promise((resolve) => setTimeout(resolve, 3000));
  }

  // Simulate EventBridge event (empty for scheduled trigger)
  const event = {
    source: "local-test",
    time: new Date().toISOString(),
  };

  console.log("Invoking Lambda handler...\n");

  try {
    const result = await handler(event);

    console.log("\n===========================================");
    console.log("  Result");
    console.log("===========================================");
    console.log(`Status Code: ${result.statusCode}`);
    console.log("");

    const body = JSON.parse(result.body);
    console.log(`Total Processed: ${body.totalProcessed || 0}`);
    console.log(`Successful: ${body.successfulCount || 0}`);
    console.log(`Failed: ${body.failedCount || 0}`);

    if (body.successful && body.successful.length > 0) {
      console.log("\nSuccessful Payouts:");
      body.successful.forEach((p) => {
        console.log(`  - Rental ${p.rentalId}: $${p.amount} (Transfer: ${p.transferId})`);
      });
    }

    if (body.failed && body.failed.length > 0) {
      console.log("\nFailed Payouts:");
      body.failed.forEach((p) => {
        console.log(`  - Rental ${p.rentalId}: ${p.error}`);
      });
    }

    if (body.totalProcessed === 0) {
      console.log("\nNo failed payouts found to retry.");
      console.log("To create test data, run:");
      console.log(`  UPDATE "Rentals" SET "payoutStatus" = 'failed' WHERE id = '<rental-id>';`);
    }
  } catch (error) {
    console.error("\nLambda execution failed:");
    console.error(error);
  }

  console.log("\n===========================================\n");
  process.exit(0);
}

runTest();
