#!/usr/bin/env tsx

// 模拟从你的日志中提取的 Stripe 订阅数据
const mockSubscriptionData = {
  "id": "sub_1Rt8nRLW0cChKPJ0Osn5UBcV",
  "object": "subscription",
  "application": null,
  "application_fee_percent": null,
  "automatic_tax": {
    "disabled_reason": null,
    "enabled": false,
    "liability": null
  },
  "billing_cycle_anchor": 1754492307,
  "billing_cycle_anchor_config": null,
  "billing_mode": {
    "type": "classic"
  },
  "billing_thresholds": null,
  "cancel_at": null,
  "cancel_at_period_end": false,
  "canceled_at": null,
  "cancellation_details": {
    "comment": null,
    "feedback": null,
    "reason": null
  },
  "collection_method": "charge_automatically",
  "created": 1754492307,
  "currency": "usd",
  "customer": "cus_SojwymqWZ4EXlZ",
  "days_until_due": null,
  "default_payment_method": "pm_1Rt8nPLW0cChKPJ0EF0QrEyS",
  "default_source": null,
  "default_tax_rates": [],
  "description": null,
  "discounts": [],
  "ended_at": null,
  "invoice_settings": {
    "account_tax_ids": null,
    "issuer": {
      "type": "self"
    }
  },
  "items": {
    "object": "list",
    "data": [
      {
        "id": "si_SomMVRu4Bpje2r",
        "object": "subscription_item",
        "billing_thresholds": null,
        "created": 1754492308,
        "current_period_end": 1757170707,
        "current_period_start": 1754492307,
        "discounts": [],
        "metadata": {},
        "plan": {
          "id": "price_1RslfmLW0cChKPJ0VurJSg9I",
          "object": "plan",
          "active": true,
          "amount": 1999,
          "amount_decimal": "1999",
          "billing_scheme": "per_unit",
          "created": 1754403422,
          "currency": "usd",
          "interval": "month",
          "interval_count": 1,
          "livemode": false,
          "metadata": {},
          "meter": null,
          "nickname": null,
          "product": "prod_SoOSFPRNsYcTF8",
          "tiers_mode": null,
          "transform_usage": null,
          "trial_period_days": null,
          "usage_type": "licensed"
        },
        "price": {
          "id": "price_1RslfmLW0cChKPJ0VurJSg9I",
          "object": "price",
          "active": true,
          "billing_scheme": "per_unit",
          "created": 1754403422,
          "currency": "usd",
          "custom_unit_amount": null,
          "livemode": false,
          "lookup_key": null,
          "metadata": {},
          "nickname": null,
          "product": "prod_SoOSFPRNsYcTF8",
          "recurring": {
            "interval": "month",
            "interval_count": 1,
            "meter": null,
            "trial_period_days": null,
            "usage_type": "licensed"
          },
          "tax_behavior": "inclusive",
          "tiers_mode": null,
          "transform_quantity": null,
          "type": "recurring",
          "unit_amount": 1999,
          "unit_amount_decimal": "1999"
        },
        "quantity": 1,
        "subscription": "sub_1Rt8nRLW0cChKPJ0Osn5UBcV",
        "tax_rates": []
      }
    ],
    "has_more": false,
    "total_count": 1,
    "url": "/v1/subscription_items?subscription=sub_1Rt8nRLW0cChKPJ0Osn5UBcV"
  },
  "latest_invoice": "in_1Rt8nPLW0cChKPJ0YOG0OCof",
  "livemode": false,
  "metadata": {},
  "next_pending_invoice_item_invoice": null,
  "on_behalf_of": null,
  "pause_collection": null,
  "payment_settings": {
    "payment_method_options": {
      "acss_debit": null,
      "bancontact": null,
      "card": {
        "network": null,
        "request_three_d_secure": "automatic"
      },
      "customer_balance": null,
      "konbini": null,
      "sepa_debit": null,
      "us_bank_account": null
    },
    "payment_method_types": [
      "card"
    ],
    "save_default_payment_method": "off"
  },
  "pending_invoice_item_interval": null,
  "pending_setup_intent": null,
  "pending_update": null,
  "plan": {
    "id": "price_1RslfmLW0cChKPJ0VurJSg9I",
    "object": "plan",
    "active": true,
    "amount": 1999,
    "amount_decimal": "1999",
    "billing_scheme": "per_unit",
    "created": 1754403422,
    "currency": "usd",
    "interval": "month",
    "interval_count": 1,
    "livemode": false,
    "metadata": {},
    "meter": null,
    "nickname": null,
    "product": "prod_SoOSFPRNsYcTF8",
    "tiers_mode": null,
    "transform_usage": null,
    "trial_period_days": null,
    "usage_type": "licensed"
  },
  "quantity": 1,
  "schedule": null,
  "start_date": 1754492307,
  "status": "active",
  "test_clock": null,
  "transfer_data": null,
  "trial_end": null,
  "trial_settings": {
    "end_behavior": {
      "missing_payment_method": "create_invoice"
    }
  },
  "trial_start": null
}

function testWebhookData() {
  console.log('🔍 Testing webhook data extraction...')
  
  const subscription = mockSubscriptionData as any
  
  console.log('📊 Subscription object keys:', Object.keys(subscription))
  
  // 测试当前的提取逻辑
  const customerId = subscription.customer as string
  const status = subscription.status as string
  const stripeSubscriptionId = subscription.id as string
  const items = subscription.items as { data: Array<{ price: { id: string } }> }
  const priceId = items?.data[0]?.price?.id
  const currentPeriodStart = subscription.current_period_start as number
  const currentPeriodEnd = subscription.current_period_end as number
  
  console.log('🎯 Extracted data (current logic):')
  console.log('  customerId:', customerId)
  console.log('  status:', status)
  console.log('  stripeSubscriptionId:', stripeSubscriptionId)
  console.log('  priceId:', priceId)
  console.log('  currentPeriodStart:', currentPeriodStart)
  console.log('  currentPeriodEnd:', currentPeriodEnd)
  
  // 检查日期是否有效
  if (currentPeriodStart) {
    const startDate = new Date(currentPeriodStart * 1000)
    console.log('  startDate:', startDate.toISOString())
  } else {
    console.log('  ❌ currentPeriodStart is undefined/null')
  }
  
  if (currentPeriodEnd) {
    const endDate = new Date(currentPeriodEnd * 1000)
    console.log('  endDate:', endDate.toISOString())
  } else {
    console.log('  ❌ currentPeriodEnd is undefined/null')
  }
  
  // 检查替代的日期字段
  console.log('\n🔍 Looking for alternative date fields:')
  console.log('  start_date:', subscription.start_date)
  console.log('  created:', subscription.created)
  console.log('  billing_cycle_anchor:', subscription.billing_cycle_anchor)
  
  // 检查 items 中的日期
  if (subscription.items?.data?.[0]) {
    const item = subscription.items.data[0]
    console.log('  item.current_period_start:', item.current_period_start)
    console.log('  item.current_period_end:', item.current_period_end)
  }
  
  console.log('\n✅ Analysis complete!')
}

testWebhookData()
