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

export const dynamic = 'force-dynamic'

export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Silakan login terlebih dahulu' }, { status: 401 })
    }

    const body = await req.json()
    const { serviceId, serviceName, serviceImg, countryName, countryImg, numberId, providerId, operatorId, basePrice } = body

    if (!serviceId || !numberId || !providerId || !operatorId || !basePrice) {
      return NextResponse.json({ error: 'Data tidak lengkap' }, { status: 400 })
    }

    // Get markup setting
    const markupSetting = await prisma.setting.findUnique({ where: { key: 'otp_markup' } })
    const markupPercent = parseFloat(markupSetting?.value || '10')
    const sellPrice = applyMarkup(basePrice, markupPercent)

    const user = await prisma.user.findUnique({ where: { id: session.user.id } })
    if (!user) return NextResponse.json({ error: 'User tidak ditemukan' }, { status: 404 })

    if (Number(user.balance) < sellPrice) {
      return NextResponse.json({ error: `Saldo tidak mencukupi. Dibutuhkan ${sellPrice}, saldo Anda ${Number(user.balance)}` }, { status: 400 })
    }

    // Deduct balance first
    const newBalance = Number(user.balance) - sellPrice

    // Create order in DB
    const otpOrder = await prisma.otpOrder.create({
      data: {
        userId: session.user.id,
        serviceId,
        serviceName,
        serviceImg,
        countryName,
        countryImg,
        numberId,
        providerId,
        operatorId,
        basePrice,
        markup: markupPercent,
        price: sellPrice,
        paymentMethod: 'balance',
        status: 'pending',
        expiresAt: new Date(Date.now() + 20 * 60 * 1000), // 20 minutes
      },
    })

    await prisma.$transaction([
      prisma.user.update({ where: { id: user.id }, data: { balance: newBalance } }),
      prisma.walletTransaction.create({
        data: {
          userId: user.id,
          type: 'PAYMENT',
          amount: sellPrice,
          balanceBefore: user.balance,
          balanceAfter: newBalance,
          status: 'SUCCESS',
          description: `OTP - ${serviceName} (${countryName})`,
          orderId: otpOrder.id,
        },
      }),
    ])

    // Call RumahOTP API
    try {
      const result = await createOtpOrder(serviceId, providerId, operatorId)
      await prisma.otpOrder.update({
        where: { id: otpOrder.id },
        data: {
          rumahOtpId: result.id,
          phoneNumber: result.number || null,
          status: 'pending',
        },
      })
      return NextResponse.json({ orderId: otpOrder.id, rumahOtpId: result.id, phoneNumber: result.number })
    } catch (apiErr: any) {
      // Refund if RumahOTP fails
      await prisma.$transaction([
        prisma.user.update({ where: { id: user.id }, data: { balance: Number(user.balance) } }),
        prisma.walletTransaction.create({
          data: {
            userId: user.id,
            type: 'REFUND',
            amount: sellPrice,
            balanceBefore: newBalance,
            balanceAfter: Number(user.balance),
            status: 'SUCCESS',
            description: `Auto Refund OTP - ${apiErr.message?.slice(0, 40)}`,
            orderId: otpOrder.id,
          },
        }),
        prisma.otpOrder.update({ where: { id: otpOrder.id }, data: { status: 'cancel' } }),
      ])
      return NextResponse.json({ error: `Gagal pesan nomor: ${apiErr.message}` }, { status: 500 })
    }
  } catch (error: any) {
    console.error('[OTP ORDER]', error)
    return NextResponse.json({ error: error.message || 'Gagal membuat pesanan OTP' }, { status: 500 })
  }
}

export async function GET(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions)
    if (!session?.user?.id) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { searchParams } = new URL(req.url)
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '10')
    const skip = (page - 1) * limit

    const [orders, total] = await Promise.all([
      prisma.otpOrder.findMany({
        where: { userId: session.user.id },
        orderBy: { createdAt: 'desc' },
        skip,
        take: limit,
      }),
      prisma.otpOrder.count({ where: { userId: session.user.id } }),
    ])

    return NextResponse.json({ orders, total, pages: Math.ceil(total / limit) })
  } catch (error) {
    console.error('[OTP LIST]', error)
    return NextResponse.json({ error: 'Gagal memuat pesanan OTP' }, { status: 500 })
  }
}
