/**
 * Klaviyo Integration E2E Test Script
 * Sends real test events to Klaviyo to verify API connectivity and email delivery
 *
 * Usage:
 *   npx tsx scripts/test-klaviyo.ts
 */

import { readFileSync } from "fs"
import { resolve } from "path"

// Load .env file before anything else (tsx doesn't auto-load env files like Next.js)
const envPath = resolve(process.cwd(), ".env")
try {
  const envContent = readFileSync(envPath, "utf-8")
  for (const line of envContent.split("\n")) {
    const trimmed = line.trim()
    if (!trimmed || trimmed.startsWith("#")) continue
    const eqIndex = trimmed.indexOf("=")
    if (eqIndex === -1) continue
    const key = trimmed.substring(0, eqIndex).trim()
    const value = trimmed.substring(eqIndex + 1).trim()
    if (!process.env[key]) {
      process.env[key] = value
    }
  }
} catch {
  console.error("Could not read .env file. Make sure it exists in the project root.")
  process.exit(1)
}

// Dynamic imports AFTER env is loaded
async function testKlaviyoIntegration() {
  const { Klaviyo } = await import("../lib/klaviyo")
  const { env } = await import("../lib/env")

  console.log("Testing Klaviyo Integration\n")

  // 1. Verify environment variables
  console.log("1. Checking environment variables...")
  const apiKey = env.KLAVIYO_API_KEY || ""
  const keyPrefix = apiKey.substring(0, 6)
  console.log(`   KLAVIYO_API_KEY: ${keyPrefix}...${apiKey.substring(apiKey.length - 4)}`)
  console.log(`   KLAVIYO_ADMIN_EMAIL: ${env.KLAVIYO_ADMIN_EMAIL || ""}`)
  console.log("")

  // 2. Build mock order (same product as EasyShip test: BPC-157 - 10 mg @ $65)
  const testEmail = "contact@mahmoudamr.dev"
  const testOrderId = 900000 + Math.floor(Math.random() * 10000) // Random to avoid unique_id collisions

  const mockOrder: any = {
    id: testOrderId,
    status: "processing",
    total: "65.00",
    currency: "USD",
    billing: {
      first_name: "Mahmoud",
      last_name: "Amr",
      email: testEmail,
      address_1: "123 Test Street",
      address_2: "Suite 100",
      city: "Los Angeles",
      state: "CA",
      postcode: "90001",
      country: "US",
    },
    shipping: {
      first_name: "Mahmoud",
      last_name: "Amr",
      address_1: "123 Test Street",
      address_2: "Suite 100",
      city: "Los Angeles",
      state: "CA",
      postcode: "90001",
      country: "US",
    },
    line_items: [
      {
        id: 1,
        name: "BPC-157 - 10 mg",
        product_id: 5001,
        quantity: 1,
        total: "65.00",
        subtotal: "65.00",
        image: { src: "https://factorpeptides.com/wp-content/uploads/bpc-157.jpg" },
      },
    ],
    shipping_lines: [
      {
        id: 1,
        method_title: "Standard Shipping",
        total: "0.00",
      },
    ],
    meta_data: [],
    customer_note: "E2E test order - Klaviyo integration",
    customer_id: 0,
    billing_email: testEmail,
  }

  const mockChargeId = "ch_test_klaviyo_e2e_" + Date.now()

  // 3. Test: Send "Placed Order" event to customer
  console.log(`2. Sending "Placed Order" event to customer (${testEmail})...`)
  console.log(`   Order #${testOrderId}: BPC-157 - 10 mg ($65.00)`)
  console.log("")

  const receiptResult = await Klaviyo.sendOrderReceipt(mockOrder, mockChargeId)

  if (receiptResult.success) {
    console.log("   SUCCESS: Order Placed event sent to customer!")
  } else {
    console.log("   FAIL: Could not send Order Placed event")
    console.log(`   Error: ${receiptResult.error}`)
  }
  console.log("")

  // 4. Test: Send "Admin Order Notification" event to admin
  console.log(`3. Sending "Admin Order Notification" event to admin (${env.KLAVIYO_ADMIN_EMAIL})...`)
  console.log("")

  const adminResult = await Klaviyo.sendAdminNotification(mockOrder, mockChargeId)

  if (adminResult.success) {
    console.log("   SUCCESS: Admin Order Notification event sent!")
  } else {
    console.log("   FAIL: Could not send Admin Order Notification event")
    console.log(`   Error: ${adminResult.error}`)
  }
  console.log("")

  // Summary
  const allPassed = receiptResult.success && adminResult.success
  console.log("─".repeat(50))
  console.log(`Klaviyo E2E test ${allPassed ? "PASSED" : "FAILED"}`)
  console.log("")

  if (allPassed) {
    console.log("Events sent successfully. Check:")
    console.log(`  1. Klaviyo dashboard → Activity Feed for order #${testOrderId}`)
    console.log(`  2. ${testEmail} inbox for the customer receipt email`)
    console.log(`  3. ${env.KLAVIYO_ADMIN_EMAIL} inbox for the admin notification email`)
    console.log("")
    console.log("Template variables available in Klaviyo email templates:")
    console.log("  {{ event.extra.OrderNumber }}")
    console.log("  {{ event.extra.OrderTotal }}")
    console.log("  {{ event|lookup:'$currency_code' }}")
    console.log("  {{ event.extra.Items.0.Name }}")
    console.log("  {{ event.extra.Items.0.Price }}")
    console.log("  {{ event.extra.Items.0.Quantity }}")
    console.log("  {{ event.extra.Items.0.ImageURL }}")
    console.log("  {{ event.extra.ShippingAddress.Address1 }}")
    console.log("  {{ event.extra.ShippingAddress.City }}")
    console.log("  {{ event.extra.ShippingAddress.State }}")
    console.log("  {{ event.extra.ShippingAddress.PostCode }}")
    console.log("  {{ event.extra.ShippingAddress.Country }}")
    console.log("  {{ event.extra.BillingAddress.FirstName }}")
    console.log("  {{ event.extra.ShippingMethod }}")
    console.log("  {{ event.extra.StripeChargeId }}")
    console.log("  {{ event.extra.PaymentMethod }}")
  } else {
    console.log("Check your KLAVIYO_API_KEY in .env and try again.")
  }
  console.log("")

  if (!allPassed) process.exit(1)
}

// Run test
testKlaviyoIntegration().catch((error) => {
  console.error("Test failed with error:")
  console.error(error)
  process.exit(1)
})
