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

export async function GET(req: NextRequest) {
  try {
    const code = req.nextUrl.searchParams.get("code");
    if (!code) {
      return NextResponse.json({ error: "Missing code" }, { status: 400 });
    }
    const clientId = process.env.NEXT_PUBLIC_CASDOOR_CLIENT_ID || "272f91105da5cf984773";
    const clientSecret = process.env.CASDOOR_CLIENT_SECRET;
    if (!clientSecret) {
      return NextResponse.json({ error: "Secret not configured" }, { status: 500 });
    }
    const redirectUri = process.env.NEXT_PUBLIC_CASDOOR_REDIRECT_URI || "https://mobile2.falahos.my/mobile/auth/callback";

    const params = new URLSearchParams();
    params.append("grant_type", "authorization_code");
    params.append("client_id", clientId);
    params.append("client_secret", clientSecret);
    params.append("code", code);
    params.append("redirect_uri", redirectUri);

    const r = await fetch("https://auth.falahos.my/api/login/oauth/access_token", {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: params,
    });

    const text = await r.text();
    let tokenData: Record<string, unknown> = {};

    try {
      tokenData = JSON.parse(text);
    } catch {
      return NextResponse.json(
        { error: "Token exchange failed", detail: text.substring(0, 200) },
        { status: 502 }
      );
    }

    if (!r.ok || tokenData.error) {
      return NextResponse.json(
        { error: tokenData.error_description || tokenData.error || "Token exchange failed" },
        { status: r.status }
      );
    }

    // Fetch user info with access token
    let user = null;
    const accessToken = tokenData.access_token as string | undefined;
    if (accessToken) {
      try {
        const u = await fetch("https://auth.falahos.my/api/userinfo", {
          headers: { Authorization: "Bearer " + accessToken },
        });
        if (u.ok) {
          user = await u.json();
        }
      } catch {
        // userinfo optional
      }
    }

    return NextResponse.json({
      access_token: accessToken,
      id_token: tokenData.id_token as string | undefined,
      refresh_token: tokenData.refresh_token as string | undefined,
      token_type: tokenData.token_type as string | undefined,
      expires_in: tokenData.expires_in as number | undefined,
      user,
    });
  } catch (e) {
    const msg = e instanceof Error ? e.message : "Error";
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
