import { NextRequest, NextResponse } from 'next/server'
import prisma from '@/lib/prisma'

export async function POST(req: NextRequest) {
  try {
    const body = await req.json()
    const { id, category, number, code, text, price, service, country, webhook } = body

    if (!id || category !== 'callback.number') {
      return NextResponse.json({ ok: true })
    }

    // Find order by rumahOtpId
    const order = await prisma.otpOrder.findUnique({
      where: { rumahOtpId: id },
    })

    if (!order) {
      console.warn('[OTP WEBHOOK] Order not found:', id)
      return NextResponse.json({ ok: true })
    }

    await prisma.otpOrder.update({
      where: { id: order.id },
      data: {
        status: 'received',
        otpCode: code || null,
        smsText: text || null,
        phoneNumber: number || order.phoneNumber,
        receivedAt: new Date(),
      },
    })

    console.log(`[OTP WEBHOOK] OTP received for order ${id}: ${code}`)
    return NextResponse.json({ ok: true })
  } catch (error) {
    console.error('[OTP WEBHOOK]', error)
    return NextResponse.json({ error: 'Webhook error' }, { status: 500 })
  }
}
