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

export async function GET(req: NextRequest) {
  try {
    const code = req.nextUrl.searchParams.get("code") || "none";
    
    // Step 1: Just try the simplest fetch
    const testUrl = "https://auth.falahos.my/api/login/oauth/access_token";
    const params = new URLSearchParams();
    params.append("grant_type", "authorization_code");
    params.append("client_id", process.env.NEXT_PUBLIC_CASDOOR_CLIENT_ID || "");
    params.append("client_secret", process.env.CASDOOR_CLIENT_SECRET || "");
    params.append("code", code);
    params.append("redirect_uri", (process.env.NEXT_PUBLIC_CASDOOR_REDIRECT_URI || "https://mobile2.falahos.my/mobile/auth/callback"));

    const res = await fetch(testUrl, {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: params,
    });

    const body = await res.text();
    
    return NextResponse.json({
      ok: true,
      code,
      hasSecret: !!process.env.CASDOOR_CLIENT_SECRET,
      casdoorStatus: res.status,
      casdoorBody: body.substring(0, 300),
    });
  } catch (e: any) {
    return NextResponse.json({ error: e.message, stack: e.stack?.substring(0, 500) }, { status: 500 });
  }
}
