/**
 * FedEx Integration Test Script
 * Run this to verify FedEx API credentials and connectivity
 *
 * Usage:
 *   npx tsx scripts/test-fedex.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 testFedExConnection() {
  const { FedEx } = await import("../lib/fedex")
  const { env } = await import("../lib/env")

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

  // 1. Verify environment variables
  console.log("1. Checking environment variables...")
  console.log(`   FEDEX_CLIENT_ID: ${(env.FEDEX_CLIENT_ID || "").substring(0, 12)}...`)
  console.log(`   FEDEX_CLIENT_SECRET: ${(env.FEDEX_CLIENT_SECRET || "").substring(0, 8)}...`)
  console.log(`   FEDEX_ACCOUNT_NUMBER: ${env.FEDEX_ACCOUNT_NUMBER || ""}`)

  const apiUrl = env.FEDEX_API_URL || "https://apis-sandbox.fedex.com"
  const isSandbox = apiUrl.includes("sandbox")
  console.log(`   FEDEX_API_URL: ${apiUrl} (${isSandbox ? "sandbox" : "production"})`)
  console.log("")

  // 2. Test OAuth authentication
  console.log("2. Testing FedEx OAuth authentication...")
  try {
    const token = await FedEx.getAccessToken()
    console.log(`   OK: Access token obtained (${token.substring(0, 20)}...)`)
  } catch (error) {
    console.log("   FAIL: OAuth authentication failed!")
    console.log(`   Error: ${error instanceof Error ? error.message : String(error)}`)
    console.log("")
    console.log("   Troubleshooting:")
    console.log("   1. Verify your FEDEX_CLIENT_ID and FEDEX_CLIENT_SECRET are correct")
    console.log("   2. Check that your FedEx Developer project is active")
    console.log("   3. For sandbox, use: https://apis-sandbox.fedex.com")
    console.log("   4. For production, use: https://apis.fedex.com")
    process.exit(1)
  }
  console.log("")

  // 3. Test shipment creation with mock order
  console.log("3. Creating test shipment...")
  console.log("   Note: This creates a REAL shipment in FedEx (sandbox)")
  console.log("   You can cancel it 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 FedEx Ship API...")
  const createResult = await FedEx.createShipment(mockOrder)

  if (createResult.success) {
    console.log("   SUCCESS: Test shipment created!")
    console.log(`   Tracking Number: ${createResult.trackingNumber}`)
    console.log(`   Ship Date: ${createResult.shipDate}`)
    console.log("")

    // 4. Test tracking
    if (createResult.trackingNumber) {
      console.log("4. Testing tracking for the shipment...")
      const trackResult = await FedEx.trackShipment(createResult.trackingNumber)

      if (trackResult.success) {
        console.log(`   Status: ${trackResult.statusDescription || trackResult.status || "N/A"}`)
        if (trackResult.events?.length) {
          console.log(`   Latest event: ${trackResult.events[0].description}`)
        }
      } else {
        console.log(`   Tracking not yet available: ${trackResult.error}`)
        console.log("   (This is normal for newly created sandbox shipments)")
      }
      console.log("")

      // 5. Skip cancellation so shipment persists in FedEx sandbox dashboard
      console.log("5. Skipping cancellation (shipment will persist in FedEx sandbox)")
      console.log("   You can view this shipment at: https://www.fedex.com/fedextrack/")
      console.log("   Or in your FedEx Developer sandbox dashboard")
      console.log("")
    }
  } 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("FedEx integration test complete!")
  console.log("")
  console.log("Next steps:")
  console.log("1. Set up FedEx webhooks for tracking updates (optional):")
  console.log("   URL: https://your-domain.com/api/fedex/webhook")
  console.log("2. Switch to production credentials when ready:")
  console.log("   FEDEX_API_URL=https://apis.fedex.com")
  console.log("3. Process a real test payment to verify end-to-end flow")
  console.log("")
}

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