import { type NextRequest, NextResponse } from "next/server"

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

    if (!email || !amount || !reference) {
      return NextResponse.json(
        {
          success: false,
          message: "Missing required fields",
        },
        { status: 400 },
      )
    }

    const paystackSecretKey = "sk_test_fc8213dd6500db9471b252e577a4011cc6d2e7bf"

    // Convert amount to kobo/cents for Paystack
    const amountInMinorUnits = Math.round(amount * 100)

    // Paystack payment initialization
    const paystackResponse = await fetch("https://api.paystack.co/transaction/initialize", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${paystackSecretKey}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        email,
        amount: amountInMinorUnits,
        reference,
        currency: currency || "GHS",
        callback_url: `${process.env.NEXT_PUBLIC_BASE_URL || "http://localhost:3000"}/payment/callback`,
        metadata: {
          student_type: studentType,
          custom_fields: [
            {
              display_name: "Student Type",
              variable_name: "student_type",
              value: studentType,
            },
          ],
        },
      }),
    })

    const data = await paystackResponse.json()

    if (data.status) {
      return NextResponse.json({
        success: true,
        authorization_url: data.data.authorization_url,
        access_code: data.data.access_code,
        reference: data.data.reference,
      })
    } else {
      console.error("Paystack initialization failed:", data)
      return NextResponse.json(
        {
          success: false,
          message: data.message || "Payment initialization failed",
        },
        { status: 400 },
      )
    }
  } catch (error) {
    console.error("Payment initialization error:", error)
    return NextResponse.json(
      {
        success: false,
        message: "Internal server error",
      },
      { status: 500 },
    )
  }
}
