/**
 * ShipStation Integration Test Script
 * Run this to verify ShipStation API credentials and connectivity
 * 
 * Usage:
 *   npx tsx scripts/test-shipstation.ts
 */

import { ShipStation } from "../lib/shipstation"
import { env } from "../lib/env"

async function testShipStationConnection() {
  console.log("🚀 Testing ShipStation Integration\n")

  // 1. Verify environment variables
  console.log("1. Checking environment variables...")
  console.log(`   ✅ SHIPSTATION_API_KEY: ${env.SHIPSTATION_API_KEY.substring(0, 8)}...`)
  console.log(`   ✅ SHIPSTATION_API_SECRET: ${env.SHIPSTATION_API_SECRET.substring(0, 8)}...`)
  
  if (env.SHIPSTATION_WEBHOOK_SECRET) {
    console.log(`   ✅ SHIPSTATION_WEBHOOK_SECRET: configured`)
  } else {
    console.log(`   ⚠️  SHIPSTATION_WEBHOOK_SECRET: not configured (optional)`)
  }
  console.log("")

  // 2. Test API connectivity (try to get a non-existent order - this will test auth)
  console.log("2. Testing ShipStation API connectivity...")
  console.log("   Attempting to fetch order #999999 (should fail with 404, not 401)...")
  
  const testResult = await ShipStation.getOrder("999999")
  
  if (testResult.success) {
    console.log("   ⚠️  Unexpected: Order found (this shouldn't happen)")
  } else if (testResult.error?.includes("401") || testResult.error?.includes("Unauthorized")) {
    console.log("   ❌ Authentication failed! Check your API credentials.")
    console.log(`   Error: ${testResult.error}`)
    process.exit(1)
  } else {
    console.log("   ✅ API authentication successful!")
    console.log(`   (Received expected error: ${testResult.error})`)
  }
  console.log("")

  // 3. Test order creation with mock data
  console.log("3. Testing order creation with mock data...")
  console.log("   Note: This creates a REAL test order in ShipStation")
  console.log("   You should delete it manually from ShipStation dashboard")
  console.log("")
  
  const mockOrder: any = {
    id: 999999,
    status: "processing",
    total: "99.99",
    currency: "USD",
    billing: {
      first_name: "Test",
      last_name: "Customer",
      email: "test@example.com",
      address_1: "123 Test Street",
      address_2: "",
      city: "Test City",
      state: "CA",
      postcode: "12345",
      country: "US",
    },
    shipping: {
      first_name: "Test",
      last_name: "Customer",
      address_1: "123 Test Street",
      address_2: "",
      city: "Test City",
      state: "CA",
      postcode: "12345",
      country: "US",
    },
    line_items: [
      {
        id: 1,
        name: "Test Product",
        product_id: 1234,
        quantity: 1,
        total: "89.99",
        subtotal: "89.99",
      },
    ],
    shipping_lines: [
      {
        id: 1,
        method_title: "Standard Shipping",
        total: "10.00",
      },
    ],
    meta_data: [],
    customer_note: "This is a test order",
    customer_id: 0,
    billing_email: "test@example.com",
  }

  console.log("   Creating test order...")
  const createResult = await ShipStation.createOrder(mockOrder)
  
  if (createResult.success) {
    console.log("   ✅ Test order created successfully!")
    console.log(`   ShipStation Order ID: ${createResult.orderId}`)
    console.log(`   Order Number: ${createResult.orderNumber}`)
    console.log("")
    console.log("   ⚠️  IMPORTANT: Delete test order #999999 from ShipStation dashboard")
  } else {
    console.log("   ❌ Failed to create test order")
    console.log(`   Error: ${createResult.error}`)
    if (createResult.errorDetails) {
      console.log(`   Details: ${JSON.stringify(createResult.errorDetails, null, 2)}`)
    }
  }
  console.log("")

  // Summary
  console.log("✅ ShipStation integration test complete!")
  console.log("")
  console.log("Next steps:")
  console.log("1. Delete test order #999999 from ShipStation dashboard")
  console.log("2. Configure ShipStation webhooks:")
  console.log("   URL: https://your-domain.com/api/shipstation/webhook")
  console.log("   Events: SHIP_NOTIFY, ITEM_SHIPPED")
  console.log("3. Process a real test payment to verify end-to-end flow")
  console.log("")
}

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




