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

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

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

    const body = await req.json()
    const { amount } = topupSchema.parse(body)

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

    // Create wallet transaction
    const tx = await prisma.walletTransaction.create({
      data: {
        userId: session.user.id,
        type: 'TOPUP',
        amount,
        balanceBefore: session.user.balance || 0,
        balanceAfter: session.user.balance || 0, // will update on payment success
        description: `Topup saldo via QRIS - Rp ${amount.toLocaleString('id-ID')}`,
        status: 'PENDING',
        invoiceId: qris.transactionId,
      },
    })

    // Log invoice
    await prisma.paymentInvoice.create({
      data: {
        transactionId: qris.transactionId,
        type: 'WALLET_TOPUP',
        userId: session.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({
      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) {
    if (error instanceof z.ZodError) {
      return NextResponse.json({ error: error.errors[0].message }, { status: 400 })
    }
    console.error('[WALLET TOPUP]', error)
    return NextResponse.json({ error: error instanceof Error ? error.message : 'Gagal membuat transaksi topup' }, { status: 500 })
  }
}

// GET - wallet transactions history
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 [transactions, total, user] = await Promise.all([
      prisma.walletTransaction.findMany({
        where: { userId: session.user.id },
        orderBy: { createdAt: 'desc' },
        skip,
        take: limit,
      }),
      prisma.walletTransaction.count({ where: { userId: session.user.id } }),
      prisma.user.findUnique({
        where: { id: session.user.id },
        select: { balance: true },
      }),
    ])

    return NextResponse.json({
      balance: user?.balance || 0,
      transactions,
      total,
      page,
      limit,
      pages: Math.ceil(total / limit),
    })
  } catch (error) {
    console.error('[WALLET GET]', error)
    return NextResponse.json({ error: 'Gagal memuat riwayat transaksi' }, { status: 500 })
  }
}
