import { type NextRequest, NextResponse } from "next/server"
import { voucherDb } from "@/lib/db"
import type { ApiResponse } from "@/lib/types"

// Generate new voucher after payment
export async function POST(request: NextRequest) {
  try {
    const { email, paymentReference } = await request.json()

    if (!email || !paymentReference) {
      return NextResponse.json<ApiResponse>(
        {
          success: false,
          error: "Email and payment reference are required",
        },
        { status: 400 },
      )
    }

    // In a real app, you would:
    // 1. Verify payment with Paystack
    // 2. Check if payment was successful
    // 3. Ensure payment hasn't been used before

    // Generate voucher
    const serialNumber = `FU2024${String(Date.now()).slice(-6)}`
    const pin = Math.floor(1000 + Math.random() * 9000).toString()

    const voucher = await voucherDb.create({
      serialNumber,
      pin,
      price: 5000,
      used: false,
      purchaseDate: new Date().toISOString(),
      email,
    })

    // In a real app, you would send email with voucher details here

    return NextResponse.json<ApiResponse>({
      success: true,
      data: {
        serialNumber: voucher.serialNumber,
        pin: voucher.pin,
        email: voucher.email,
      },
      message: "Voucher generated successfully",
    })
  } catch (error) {
    console.error("Generate voucher error:", error)
    return NextResponse.json<ApiResponse>(
      {
        success: false,
        error: "Internal server error",
      },
      { status: 500 },
    )
  }
}
