import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'
import { getOtpOrderStatus, setOtpOrderStatus, OtpOrderAction } from '@/lib/rumahotp'

export const dynamic = 'force-dynamic'

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

    const order = await prisma.otpOrder.findFirst({
      where: { id: params.id, userId: session.user.id },
    })

    if (!order) return NextResponse.json({ error: 'Pesanan tidak ditemukan' }, { status: 404 })

    // If still pending, check latest status from RumahOTP
    if (order.status === 'pending' && order.rumahOtpId) {
      try {
        const apiStatus = await getOtpOrderStatus(order.rumahOtpId)
        if (apiStatus.code || apiStatus.status === 'received') {
          await prisma.otpOrder.update({
            where: { id: order.id },
            data: {
              status: 'received',
              otpCode: apiStatus.code || null,
              smsText: apiStatus.text || null,
              phoneNumber: apiStatus.number || order.phoneNumber,
              receivedAt: new Date(),
            },
          })
          return NextResponse.json({ order: { ...order, status: 'received', otpCode: apiStatus.code, smsText: apiStatus.text, phoneNumber: apiStatus.number } })
        }
      } catch { /* ignore poll errors */ }
    }

    return NextResponse.json({ order })
  } catch (error) {
    console.error('[OTP STATUS]', error)
    return NextResponse.json({ error: 'Gagal cek status' }, { status: 500 })
  }
}

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

    const { action } = await req.json() as { action: OtpOrderAction }
    if (!['cancel', 'done', 'resend'].includes(action)) {
      return NextResponse.json({ error: 'Aksi tidak valid' }, { status: 400 })
    }

    const order = await prisma.otpOrder.findFirst({
      where: { id: params.id, userId: session.user.id },
    })
    if (!order || !order.rumahOtpId) return NextResponse.json({ error: 'Pesanan tidak ditemukan' }, { status: 404 })

    await setOtpOrderStatus(order.rumahOtpId, action)

    if (action === 'cancel') {
      // Auto refund
      const user = await prisma.user.findUnique({ where: { id: session.user.id } })
      if (user) {
        const refundBalance = Number(user.balance) + Number(order.price)
        await prisma.$transaction([
          prisma.otpOrder.update({ where: { id: order.id }, data: { status: 'cancel' } }),
          prisma.user.update({ where: { id: user.id }, data: { balance: refundBalance } }),
          prisma.walletTransaction.create({
            data: {
              userId: user.id,
              type: 'REFUND',
              amount: order.price,
              balanceBefore: user.balance,
              balanceAfter: refundBalance,
              status: 'SUCCESS',
              description: `Refund OTP - ${order.serviceName} dibatalkan`,
              orderId: order.id,
            },
          }),
        ])
      }
    } else if (action === 'done') {
      await prisma.otpOrder.update({ where: { id: order.id }, data: { status: 'done' } })
    } else if (action === 'resend') {
      await prisma.otpOrder.update({ where: { id: order.id }, data: { otpCode: null, smsText: null } })
    }

    const updated = await prisma.otpOrder.findUnique({ where: { id: order.id } })
    return NextResponse.json({ order: updated })
  } catch (error: any) {
    console.error('[OTP PATCH]', error)
    return NextResponse.json({ error: error.message || 'Gagal ubah status' }, { status: 500 })
  }
}
