import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import { stripe } from '@/lib/stripe'
import { prisma } from '@/lib/prisma'

export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user) {
      return NextResponse.json({ error: 'Não autenticado' }, { status: 401 })
    }

    const { priceId } = await req.json()
    if (!priceId) {
      return NextResponse.json({ error: 'Price ID é obrigatório' }, { status: 400 })
    }

    const user = await prisma.user.findUnique({
      where: { id: session.user.id },
    })

    if (!user) {
      return NextResponse.json({ error: 'Usuário não encontrado' }, { status: 404 })
    }

    // Get or create Stripe customer
    let customerId = user.stripeCustomerId

    if (customerId) {
      // Verify the stored customer still exists in Stripe
      try {
        await stripe.customers.retrieve(customerId)
      } catch (err: any) {
        // Customer doesn't exist in Stripe (e.g., from test mode or deleted)
        console.warn(`Stripe customer ${customerId} not found, creating new one for user ${user.id}`)
        customerId = null

        // Clear stale Stripe data in the database
        await prisma.user.update({
          where: { id: user.id },
          data: {
            stripeCustomerId: null,
            stripeSubscriptionId: null,
            stripePriceId: null,
          },
        })
      }
    }

    if (!customerId) {
      const customer = await stripe.customers.create({
        email: user.email,
        name: user.name,
        metadata: { userId: user.id },
      })
      customerId = customer.id

      await prisma.user.update({
        where: { id: user.id },
        data: { stripeCustomerId: customerId },
      })
    }

    // Create checkout session
    const checkoutSession = await stripe.checkout.sessions.create({
      customer: customerId,
      mode: 'subscription',
      payment_method_types: ['card'],
      line_items: [{ price: priceId, quantity: 1 }],
      success_url: `https://lexmind.adv.br/adv/dashboard?upgrade=success`,
      cancel_url: `https://lexmind.adv.br/adv/pricing`,
      allow_promotion_codes: true,
      metadata: { userId: user.id },
      subscription_data: {
        metadata: { userId: user.id },
      },
    })

    return NextResponse.json({ url: checkoutSession.url })
  } catch (error: any) {
    console.error('Stripe checkout error:', error)
    return NextResponse.json(
      { error: 'Erro ao criar sessão de checkout' },
      { status: 500 }
    )
  }
}
