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

const ALLOWED_CLIENT_IDS = new Set(["cf_vscode_app", "cf-cli-app"])

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { grant_type, code, redirect_uri, code_verifier, client_id } = body

    if (grant_type !== "authorization_code") {
      return NextResponse.json({ error: "unsupported_grant_type" }, { status: 400 })
    }

    if (!code || !redirect_uri || !code_verifier || !client_id) {
      return NextResponse.json(
        { error: "invalid_request", error_description: "Missing required parameters" },
        { status: 400 },
      )
    }

    if (!ALLOWED_CLIENT_IDS.has(client_id)) {
      return NextResponse.json({ error: "invalid_client" }, { status: 401 })
    }

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

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

    return NextResponse.json({
      access_token: result.accessToken,
      token_type: "Bearer",
    })
  } catch {
    return NextResponse.json(
      { error: "server_error", error_description: "Internal server error" },
      { status: 500 },
    )
  }
}
