/**
 * EasyShip Integration Test Script
 * Run this to verify EasyShip API credentials and connectivity
 *
 * Usage:
 *   npx tsx scripts/test-easyship.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 (ESM hoists static imports, so we must use dynamic import)
async function testEasyShipConnection() {
  const { EasyShip } = await import("../lib/easyship")
  const { env } = await import("../lib/env")

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

  // 1. Verify environment variables
  console.log("1. Checking environment variables...")
  const tokenPrefix = env.EASYSHIP_API_TOKEN.substring(0, 5)
  const tokenEnv = tokenPrefix.startsWith("prod_") ? "production" : "sandbox"
  console.log(`   EASYSHIP_API_TOKEN: ${env.EASYSHIP_API_TOKEN.substring(0, 12)}... (${tokenEnv})`)

  if (env.EASYSHIP_WEBHOOK_SECRET) {
    console.log(`   EASYSHIP_WEBHOOK_SECRET: configured`)
  } else {
    console.log(`   EASYSHIP_WEBHOOK_SECRET: not configured (optional)`)
  }
  console.log("")

  // 2. Test API connectivity (try to get a non-existent shipment - this will test auth)
  console.log("2. Testing EasyShip API connectivity...")
  console.log("   Attempting to fetch shipment 'test-nonexistent' (should fail with 404, not 401)...")

  const testResult = await EasyShip.getShipment("test-nonexistent")

  if (testResult.success) {
    console.log("   Unexpected: Shipment found (this shouldn't happen)")
  } else if (testResult.error?.includes("401") || testResult.error?.toLowerCase().includes("unauthorized")) {
    console.log("   FAIL: Authentication failed! Check your API token.")
    console.log(`   Error: ${testResult.error}`)
    process.exit(1)
  } else {
    console.log("   OK: API authentication successful!")
    console.log(`   (Received expected error: ${testResult.error})`)
  }
  console.log("")

  // 3. Test shipment creation with real product: BPC-157 - 10 mg @ $65
  console.log("3. Creating test shipment: BPC-157 - 10 mg ($65.00)...")
  console.log("   Note: This creates a REAL shipment in EasyShip")
  console.log("   You should delete it manually from EasyShip dashboard after testing")
  console.log("")

  const mockOrder: any = {
    id: 100001,
    status: "processing",
    total: "65.00",
    currency: "USD",
    billing: {
      first_name: "Test",
      last_name: "Customer",
      email: "test@example.com",
      address_1: "123 Test Street",
      address_2: "",
      city: "Los Angeles",
      state: "CA",
      postcode: "90001",
      country: "US",
    },
    shipping: {
      first_name: "Test",
      last_name: "Customer",
      address_1: "123 Test Street",
      address_2: "",
      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",
      },
    ],
    shipping_lines: [
      {
        id: 1,
        method_title: "Standard Shipping",
        total: "0.00",
      },
    ],
    meta_data: [],
    customer_note: "Test order - BPC-157 10mg",
    customer_id: 0,
    billing_email: "test@example.com",
  }

  console.log("   Sending to EasyShip API...")
  const createResult = await EasyShip.createShipment(mockOrder)

  if (createResult.success) {
    console.log("   SUCCESS: Test shipment created!")
    console.log(`   EasyShip Shipment ID: ${createResult.shipmentId}`)
    console.log(`   Platform Order Number: ${createResult.platformOrderNumber}`)
    console.log("")
    console.log("   IMPORTANT: Delete the test shipment from EasyShip dashboard")
  } else {
    console.log("   FAIL: Failed to create test shipment")
    console.log(`   Error: ${createResult.error}`)
    if (createResult.errorDetails) {
      console.log(`   Details: ${JSON.stringify(createResult.errorDetails, null, 2)}`)
    }
  }
  console.log("")

  // Summary
  console.log("EasyShip integration test complete!")
  console.log("")
  console.log("Next steps:")
  console.log("1. Delete any test shipments from EasyShip dashboard")
  console.log("2. Configure EasyShip webhooks:")
  console.log("   URL: https://your-domain.com/api/easyship/webhook")
  console.log("   Events: shipment.tracking.statuschanged, shipment.label.created, shipment.label.failed")
  console.log("3. Process a real test payment to verify end-to-end flow")
  console.log("")
}

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