import { type NextRequest, NextResponse } from "next/server"
import { createClient } from "@/lib/supabase/server"

export async function POST(request: NextRequest) {
  try {
    const { reference, studentType, email } = await request.json()

    if (!reference) {
      return NextResponse.json(
        {
          success: false,
          message: "Payment reference is required",
        },
        { status: 400 },
      )
    }

    const paystackSecretKey = "sk_test_fc8213dd6500db9471b252e577a4011cc6d2e7bf"

    // Verify payment with Paystack
    const paystackResponse = await fetch(`https://api.paystack.co/transaction/verify/${reference}`, {
      method: "GET",
      headers: {
        Authorization: `Bearer ${paystackSecretKey}`,
      },
    })

    const paystackData = await paystackResponse.json()

    if (paystackData.status && paystackData.data.status === "success") {
      // Payment verified successfully, now generate voucher
      const supabase = await createClient()

      // Generate voucher details
      const serialNumber = `FU${new Date().getFullYear()}${String(Date.now()).slice(-6)}`
      const pin = Math.floor(1000 + Math.random() * 9000).toString()
      const amount = paystackData.data.amount / 100 // Convert from kobo/cents
      const currency = paystackData.data.currency

      // Insert payment record
      const { data: paymentData, error: paymentError } = await supabase
        .from("payments")
        .insert({
          reference: paystackData.data.reference,
          email: paystackData.data.customer.email,
          amount,
          currency,
          status: "completed",
          gateway_response: paystackData.data,
        })
        .select()
        .single()

      if (paymentError) {
        console.error("Payment record creation error:", paymentError)
        return NextResponse.json(
          {
            success: false,
            message: "Failed to record payment",
          },
          { status: 500 },
        )
      }

      // Insert voucher record
      const { data: voucherData, error: voucherError } = await supabase
        .from("vouchers")
        .insert({
          serial_number: serialNumber,
          pin,
          student_type: studentType,
          price: amount,
          currency,
          email: paystackData.data.customer.email,
          payment_reference: reference,
          status: "active",
        })
        .select()
        .single()

      if (voucherError) {
        console.error("Voucher creation error:", voucherError)
        return NextResponse.json(
          {
            success: false,
            message: "Failed to generate voucher",
          },
          { status: 500 },
        )
      }

      // Update payment with voucher ID
      await supabase.from("payments").update({ voucher_id: voucherData.id }).eq("id", paymentData.id)

      // Send email with voucher details (will be implemented in next task)
      try {
        await fetch(`${process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:3000"}/api/emails/send`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            type: "voucher_delivery",
            email: paystackData.data.customer.email,
            voucher: voucherData,
            studentType,
          }),
        })
      } catch (emailError) {
        console.error("Email sending error:", emailError)
        // Don't fail the whole process if email fails
      }

      return NextResponse.json({
        success: true,
        payment: paystackData.data,
        voucher: voucherData,
      })
    } else {
      return NextResponse.json(
        {
          success: false,
          message: "Payment verification failed",
        },
        { status: 400 },
      )
    }
  } catch (error) {
    console.error("Payment verification error:", error)
    return NextResponse.json(
      {
        success: false,
        message: "Internal server error",
      },
      { status: 500 },
    )
  }
}
