import { NextRequest, NextResponse } from "next/server"
import { exchangeCodeForToken } from "../../action"

export async function POST(request: NextRequest) {
  console.log("=== Token Exchange Request Started ===")

  try {
    const body = await request.json()
    console.log("Request body:", {
      grant_type: body.grant_type,
      client_id: body.client_id,
      redirect_uri: body.redirect_uri,
      has_code: !!body.code,
      has_code_verifier: !!body.code_verifier,
      code_length: body.code?.length,
      code_verifier_length: body.code_verifier?.length,
    })

    const { grant_type, code, redirect_uri, code_verifier, client_id } = body

    // Validate grant type
    if (grant_type !== "authorization_code") {
      console.error("Invalid grant type:", grant_type)
      return NextResponse.json({ error: "unsupported_grant_type" }, { status: 400 })
    }

    // Validate required parameters
    if (!code || !redirect_uri || !code_verifier || !client_id) {
      console.error("Missing required parameters:", {
        has_code: !!code,
        has_redirect_uri: !!redirect_uri,
        has_code_verifier: !!code_verifier,
        has_client_id: !!client_id,
      })
      return NextResponse.json(
        { error: "invalid_request", error_description: "Missing required parameters" },
        { status: 400 },
      )
    }

    console.log("Exchanging code for token...")

    const result = await exchangeCodeForToken({
      code,
      codeVerifier: code_verifier,
      redirectUri: redirect_uri,
      clientId: client_id,
    })

    if (result.error) {
      console.error("Token exchange failed:", result.error)
      return NextResponse.json(
        { error: "invalid_grant", error_description: result.error },
        { status: 400 },
      )
    }

    console.log("=== Token Exchange Request Completed Successfully ===")

    return NextResponse.json({
      access_token: result.accessToken,
      token_type: "Bearer",
    })
  } catch (error) {
    console.error("=== Token Exchange Request Failed ===")
    console.error("Error type:", error instanceof Error ? error.constructor.name : typeof error)
    console.error("Error message:", error instanceof Error ? error.message : String(error))
    console.error("Error stack:", error instanceof Error ? error.stack : "No stack trace")
    console.error("Full error object:", error)

    return NextResponse.json(
      { error: "server_error", error_description: "Internal server error" },
      { status: 500 },
    )
  }
}
