import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import prisma from '@/lib/prisma'
import { authenticateH2H, h2hUnauthorized } from '@/lib/h2h-auth'
import { generateQris, getQrImageUrl } from '@/lib/cashify'

const depositSchema = z.object({
  amount: z.number()
    .min(10000, 'Minimal deposit Rp 10.000')
    .max(10000000, 'Maksimal deposit Rp 10.000.000'),
})

export async function POST(req: NextRequest) {
  try {
    const user = await authenticateH2H(req)
    if (!user) return h2hUnauthorized()

    const body = await req.json().catch(() => ({}))
    
    let amount: number
    try {
      const parsed = depositSchema.parse(body)
      amount = parsed.amount
    } catch (e: any) {
      if (e instanceof z.ZodError) {
        return NextResponse.json({ success: false, error: e.errors[0].message }, { status: 400 })
      }
      return NextResponse.json({ success: false, error: 'Format request tidak valid' }, { status: 400 })
    }

    // Generate QRIS via Cashify
    const qris = await generateQris({
      amount,
      expiredInMinutes: 30,
      useUniqueCode: true,
    })

    // Create wallet transaction (status PENDING)
    const tx = await prisma.walletTransaction.create({
      data: {
        userId: user.id,
        type: 'TOPUP',
        amount,
        balanceBefore: user.balance,
        balanceAfter: user.balance, // will be updated upon successful payment in webhook
        description: `Deposit API (H2H) via QRIS - Rp ${amount.toLocaleString('id-ID')}`,
        status: 'PENDING',
        invoiceId: qris.transactionId,
      },
    })

    // Create payment invoice for webhook tracking
    await prisma.paymentInvoice.create({
      data: {
        transactionId: qris.transactionId,
        type: 'WALLET_TOPUP',
        userId: user.id,
        walletTxId: tx.id,
        amount,
        totalAmount: qris.totalAmount,
        uniqueCode: qris.uniqueNominal,
        qrString: qris.qr_string,
        status: 'pending',
        packageIds: JSON.stringify(qris.packageIds),
        expiredAt: new Date(Date.now() + 30 * 60 * 1000),
      },
    })

    return NextResponse.json({
      success: true,
      message: 'Silakan lakukan pembayaran sesuai instruksi',
      data: {
        transactionId: tx.id,
        invoiceId: qris.transactionId,
        amount,
        totalAmount: qris.totalAmount,
        uniqueCode: qris.uniqueNominal,
        qrString: qris.qr_string,
        qrImageUrl: getQrImageUrl(qris.qr_string),
        expiresAt: new Date(Date.now() + 30 * 60 * 1000).toISOString(),
      }
    })
  } catch (error: any) {
    console.error('[H2H DEPOSIT]', error)
    return NextResponse.json({ 
      success: false, 
      error: error.message || 'Gagal memproses permintaan deposit' 
    }, { status: 500 })
  }
}
