import { NextRequest, NextResponse } from 'next/server'
import { stripe, STRIPE_CONFIG } from '@/lib/stripe'
import { prisma } from '@/lib/prisma'
import { headers } from 'next/headers'
import { SubscriptionService } from '@/lib/subscription-service'
import { addCreditForSubscription, recordSubscriptionPayment, addCreditForSubscriptionRefund, addCredit } from '@/lib/services/credit'

export async function POST(request: NextRequest) {
  try {
    console.log('🔔 Webhook received')
    const body = await request.text()
    const headersList = await headers()
    const signature = headersList.get('stripe-signature')

    if (!signature) {
      console.log('❌ No signature found')
      return NextResponse.json({ error: 'No signature' }, { status: 400 })
    }

    // 验证 webhook 签名
    const event = stripe.webhooks.constructEvent(
      body,
      signature,
      STRIPE_CONFIG.webhookSecret
    )

    console.log(`📨 Processing event: ${event.type}`)

    // 处理不同类型的事件
    switch (event.type) {
      case 'checkout.session.completed':
        await handleCheckoutSessionCompleted(event.data.object as unknown as Record<string, unknown>)
        break

      case 'customer.subscription.created':
        await handleSubscriptionCreated(event.data.object as unknown as Record<string, unknown>)
        break

      case 'customer.subscription.updated':
        await handleSubscriptionUpdate(event.data.object as unknown as Record<string, unknown>)
        break

      case 'customer.subscription.deleted':
        await handleSubscriptionDeleted(event.data.object as unknown as Record<string, unknown>)
        break

      case 'invoice.payment_succeeded':
        await handlePaymentSucceeded(event.data.object as unknown as Record<string, unknown>)
        break

      case 'invoice.payment_failed':
        await handlePaymentFailed()
        break

      default:
        console.log(`Unhandled event type: ${event.type}`)
    }

    return NextResponse.json({ received: true })

  } catch (error) {
    console.error('Webhook error:', error)
    return NextResponse.json(
      { error: 'Webhook handler failed' },
      { status: 400 }
    )
  }
}

async function handleCheckoutSessionCompleted(session: Record<string, unknown>) {
  try {
    console.log('🛒 Processing checkout session completed')
    console.log('Session data:', JSON.stringify(session, null, 2))

    const mode = session.mode as string
    const paymentStatus = session.payment_status as string
    const customerId = session.customer as string
    const sessionId = session.id as string

    console.log('Session details:', { mode, paymentStatus, customerId, sessionId })

    if (paymentStatus !== 'paid') {
      console.log('❌ Payment not completed, skipping')
      return
    }

    if (mode === 'payment') {
      // 处理一次性支付（充值）
      await handleOneTimePayment(session)
    } else if (mode === 'subscription') {
      // 处理订阅支付
      const subscriptionId = session.subscription as string
      console.log('Subscription ID from session:', subscriptionId)

      if (!subscriptionId) {
        console.log('❌ No subscription ID found in checkout session')
        return
      }

      // 获取订阅详情
      console.log('📞 Retrieving subscription from Stripe...')
      const subscription = await stripe.subscriptions.retrieve(subscriptionId)
      console.log('✅ Retrieved subscription:', subscription.id, 'status:', subscription.status)

      // 处理订阅更新
      await handleSubscriptionUpdate(subscription as unknown as Record<string, unknown>)
    }

  } catch (error) {
    console.error('❌ Error handling checkout session completed:', error)
  }
}

async function handleSubscriptionCreated(subscription: Record<string, unknown>) {
  try {
    console.log('🆕 Processing subscription created')
    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 }
      current_period_start: number
      current_period_end: number
    }> }
    const priceId = items?.data[0]?.price?.id

    // 从 subscription items 中获取周期日期，如果不存在则使用 subscription 的 start_date
    const currentPeriodStart = items?.data[0]?.current_period_start || subscription.start_date as number
    const currentPeriodEnd = items?.data[0]?.current_period_end || (subscription.start_date as number + 30 * 24 * 60 * 60) // 默认30天后

    console.log(`📊 New subscription details:`, {
      customerId,
      status,
      stripeSubscriptionId,
      priceId,
      currentPeriodStart,
      currentPeriodEnd
    })

    // 验证必要的字段
    if (!customerId || !stripeSubscriptionId || !priceId) {
      console.error('❌ Missing required subscription data:', {
        customerId: !!customerId,
        stripeSubscriptionId: !!stripeSubscriptionId,
        priceId: !!priceId
      })
      return
    }

    // 验证日期字段
    if (!currentPeriodStart || !currentPeriodEnd) {
      console.error('❌ Missing or invalid period dates:', {
        currentPeriodStart,
        currentPeriodEnd
      })
      return
    }

    // 查找用户 - 使用原始查询避免类型问题
    const users = await prisma.$queryRaw<Array<{id: string, email: string, stripeCustomerId: string}>>`
      SELECT id, email, "stripeCustomerId"
      FROM users
      WHERE "stripeCustomerId" = ${customerId}
      LIMIT 1
    `
    const user = users[0] || null

    if (!user) {
      console.error('❌ User not found for customer:', customerId)
      return
    }

    console.log(`👤 Found user: ${user.id}`)

    if (status === 'active' || status === 'trialing') {
      // 根据 Stripe 价格 ID 获取套餐 ID
      const planId = await SubscriptionService.getPlanIdByStripePriceId(priceId)

      // 创建日期对象，确保有效性
      const startDate = new Date(currentPeriodStart * 1000)
      const endDate = new Date(currentPeriodEnd * 1000)

      console.log(`📅 Subscription dates:`, {
        currentPeriodStart,
        currentPeriodEnd,
        startDate: startDate.toISOString(),
        endDate: endDate.toISOString()
      })

      // 创建新的订阅记录
      const newSubscription = await SubscriptionService.createRenewalSubscription(
        user.id,
        planId,
        stripeSubscriptionId,
        startDate,
        endDate,
        customerId,
        subscription
      )

      console.log(`✅ Created new subscription ${newSubscription.id} for user ${user.id}`)

      // 更新用户的默认订阅套餐（保持向后兼容）
      await SubscriptionService.updateUserSubscriptionPlan(user.id, planId)
    }

  } catch (error) {
    console.error('❌ Error handling subscription created:', error)
  }
}

async function handleSubscriptionUpdate(subscription: Record<string, unknown>) {
  try {
    console.log('🔄 Processing subscription update')
    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 }
      current_period_start: number
      current_period_end: number
    }> }
    const priceId = items?.data[0]?.price?.id

    // 从 subscription items 中获取周期日期
    const currentPeriodStart = items?.data[0]?.current_period_start || subscription.start_date as number
    const currentPeriodEnd = items?.data[0]?.current_period_end || (subscription.start_date as number + 30 * 24 * 60 * 60)

    console.log(`📊 Subscription details:`, {
      customerId,
      status,
      stripeSubscriptionId,
      priceId
    })

    // 查找用户
    const users = await prisma.$queryRaw<Array<{id: string, email: string, stripeCustomerId: string}>>`
      SELECT id, email, "stripeCustomerId"
      FROM users
      WHERE "stripeCustomerId" = ${customerId}
      LIMIT 1
    `
    const user = users[0] || null

    if (!user) {
      console.error('❌ User not found for customer:', customerId)
      return
    }

    console.log(`👤 Found user: ${user.id}`)

    if (status === 'active' || status === 'trialing') {
      // 根据 Stripe 价格 ID 获取套餐 ID
      const planId = await SubscriptionService.getPlanIdByStripePriceId(priceId)

      // 查找现有的订阅记录（通过 Stripe 订阅 ID）
      const existingSubscriptions = await prisma.$queryRaw<Array<{id: string, userId: string, status: string}>>`
        SELECT id, "userId", status
        FROM subscriptions
        WHERE "stripeSubscriptionId" = ${stripeSubscriptionId}
        LIMIT 1
      `
      const existingSubscription = existingSubscriptions[0] || null

      if (existingSubscription) {
        // 更新现有的订阅记录
        await prisma.$executeRaw`
          UPDATE subscriptions
          SET
            "isActive" = true,
            status = 'active',
            "startDate" = ${new Date(currentPeriodStart * 1000)},
            "endDate" = ${new Date(currentPeriodEnd * 1000)},
            metadata = ${subscription ? JSON.stringify(subscription) : null}::jsonb,
            "updatedAt" = NOW()
          WHERE id = ${existingSubscription.id}
        `
        console.log(`✅ Updated existing subscription ${existingSubscription.id} for user ${user.id}`)

        // 更新用户的默认订阅套餐（保持向后兼容）
        await SubscriptionService.updateUserSubscriptionPlan(user.id, planId)
      } else {
        console.log(`⚠️ No existing subscription found for Stripe subscription ${stripeSubscriptionId}`)
      }
    }

    // 更新用户的默认订阅套餐（保持向后兼容）
    const planId = status === 'active' || status === 'trialing'
      ? await SubscriptionService.getPlanIdByStripePriceId(priceId)
      : 'free'
    await SubscriptionService.updateUserSubscriptionPlan(user.id, planId)

  } catch (error) {
    console.error('Error handling subscription update:', error)
  }
}

async function handleSubscriptionDeleted(subscription: Record<string, unknown>) {
  try {
    const customerId = subscription.customer as string
    const stripeSubscriptionId = subscription.id as string

    // 查找用户
    const users = await prisma.$queryRaw<Array<{id: string, email: string, stripeCustomerId: string}>>`
      SELECT id, email, "stripeCustomerId"
      FROM users
      WHERE "stripeCustomerId" = ${customerId}
      LIMIT 1
    `
    const user = users[0] || null

    if (!user) {
      console.error('User not found for customer:', customerId)
      return
    }

    // 查找对应的数据库订阅记录
    const dbSubscription = await prisma.subscription.findFirst({
      where: { stripeSubscriptionId: stripeSubscriptionId },
      include: { subscriptionPlan: true }
    })

    if (dbSubscription) {
      // 标记数据库中的订阅为已取消
      await prisma.subscription.update({
        where: { id: dbSubscription.id },
        data: {
          isActive: false,
          status: 'canceled',
          updatedAt: new Date()
        }
      })

      console.log(`✅ Marked subscription ${dbSubscription.id} as canceled in database`)

      // TODO: 如果需要记录退款，可以在这里添加
      // 这取决于具体的退款政策和Stripe配置
      // const refundAmount = calculateRefundAmount(dbSubscription)
      // if (refundAmount > 0) {
      //   await addCreditForSubscriptionRefund(
      //     user.id,
      //     refundAmount,
      //     dbSubscription.id,
      //     dbSubscription.subscriptionPlan.displayName,
      //     `Refund for canceled ${dbSubscription.subscriptionPlan.displayName} subscription`
      //   )
      // }
    }

    // 将用户降级为免费计划
    await SubscriptionService.updateUserSubscriptionPlan(user.id, 'free')

    console.log(`Reset user ${user.id} to free plan`)
  } catch (error) {
    console.error('Error handling subscription deletion:', error)
  }
}

async function handlePaymentSucceeded(invoice: Record<string, unknown>) {
  try {
    console.log('💰 Processing payment succeeded')

    const subscriptionId = invoice.subscription as string
    const customerId = invoice.customer as string
    const amountPaid = (invoice.amount_paid as number) / 100 // Stripe amounts are in cents

    console.log('Payment details:', {
      subscriptionId,
      customerId,
      amount: amountPaid,
      status: invoice.status
    })

    if (!subscriptionId) {
      console.log('❌ No subscription ID found in invoice, skipping')
      return
    }

    // 查找用户
    const users = await prisma.$queryRaw<Array<{id: string, email: string, stripeCustomerId: string}>>`
      SELECT id, email, "stripeCustomerId"
      FROM users
      WHERE "stripeCustomerId" = ${customerId}
      LIMIT 1
    `
    const user = users[0] || null

    if (!user) {
      console.error('❌ User not found for customer:', customerId)
      return
    }

    // 获取订阅详情
    console.log('📞 Retrieving subscription from Stripe...')
    const subscription = await stripe.subscriptions.retrieve(subscriptionId)
    console.log('✅ Retrieved subscription:', subscription.id, 'status:', subscription.status)

    // 获取套餐信息
    const priceId = subscription.items.data[0]?.price?.id
    if (priceId) {
      const plan = await prisma.subscriptionPlan.findFirst({
        where: { stripePriceId: priceId, isActive: true }
      })

      if (plan) {
        // 查找对应的数据库订阅记录
        const dbSubscription = await prisma.subscription.findFirst({
          where: { stripeSubscriptionId: subscriptionId }
        })

        if (dbSubscription) {
          console.log('💳 Recording subscription payment and credit')

          // 1. 记录订阅付费支出（可选，如果想跟踪用户支出）
          // await recordSubscriptionPayment(
          //   user.id,
          //   amountPaid,
          //   dbSubscription.id,
          //   plan.displayName,
          //   `${plan.displayName} subscription payment - ${new Date().toISOString().slice(0, 7)}`
          // )

          // 2. 获取套餐配置中的月度信用额度
          const planLimits = plan.limits as { creditMonthly?: number }
          const monthlyCreditAmount = planLimits?.creditMonthly || 0

          if (monthlyCreditAmount > 0) {
            // 添加月度信用额度
            await addCreditForSubscription(
              user.id,
              monthlyCreditAmount,
              dbSubscription.id,
              plan.displayName,
              `${plan.displayName} monthly credit allowance - ${new Date().toISOString().slice(0, 7)}`
            )

            console.log(`✅ Added ${monthlyCreditAmount} USD monthly credit for user ${user.id}`)
          }
        }
      }
    }

    // 处理订阅更新（激活逻辑）
    await handleSubscriptionUpdate(subscription as unknown as Record<string, unknown>)

  } catch (error) {
    console.error('❌ Error handling payment success:', error)
  }
}

async function handleOneTimePayment(session: Record<string, unknown>) {
  try {
    console.log('💳 Processing one-time payment (credit top-up)')
    
    const customerId = session.customer as string
    const sessionId = session.id as string
    const metadata = session.metadata as Record<string, unknown> || {}
    const amountTotal = (session.amount_total as number) / 100 // Convert from cents to dollars

    console.log('Payment details:', {
      customerId,
      sessionId,
      amountTotal,
      metadata
    })

    // 检查是否是充值类型
    if (metadata.type !== 'credit_topup') {
      console.log('❌ Not a credit top-up payment, skipping')
      return
    }

    // 查找用户
    const users = await prisma.$queryRaw<Array<{id: string, email: string, stripeCustomerId: string}>>`
      SELECT id, email, "stripeCustomerId"
      FROM users
      WHERE "stripeCustomerId" = ${customerId}
      LIMIT 1
    `
    const user = users[0] || null

    if (!user) {
      console.error('❌ User not found for customer:', customerId)
      return
    }

    console.log(`👤 Found user: ${user.id}`)

    // 检查是否已经处理过这个支付会话
    const existingCredit = await prisma.credit.findFirst({
      where: {
        referenceId: sessionId,
        referenceType: 'stripe_payment'
      }
    })

    if (existingCredit) {
      console.log('⚠️ Payment already processed, skipping')
      return
    }

    // 添加信用额度
    const creditTransaction = await addCredit(
      user.id,
      amountTotal,
      'user_purchase',
      `Stripe payment: $${amountTotal}`
    )

    // 更新 credit 记录的 referenceId 和 referenceType
    await prisma.credit.update({
      where: { id: creditTransaction.id },
      data: {
        referenceId: sessionId,
        referenceType: 'stripe_payment'
      }
    })

    console.log(`✅ Successfully added $${amountTotal} credit for user ${user.id}`)
    console.log(`📊 Transaction ID: ${creditTransaction.id}`)

  } catch (error) {
    console.error('❌ Error handling one-time payment:', error)
  }
}

async function handlePaymentFailed() {
  try {
    // 这里可以添加额外的逻辑，比如发送提醒邮件等

  } catch (error) {
    console.error('Error handling payment failure:', error)
  }
}
