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

const CLIENT_ID = process.env.NEXT_PUBLIC_CASDOOR_CLIENT_ID || "272f91105da5cf984773";
const CLIENT_SECRET = process.env.CASDOOR_CLIENT_SECRET;
const CASDOOR_TOKEN_URL = "https://auth.falahos.my/api/login/oauth/access_token";
const CASDOOR_USERINFO_URL = "https://auth.falahos.my/api/userinfo";

export async function GET(req: NextRequest) {
  try {
    const code = req.nextUrl.searchParams.get("code");
    const state = req.nextUrl.searchParams.get("state");

    if (!code) {
      return NextResponse.json({ error: "Missing authorization code" }, { status: 400 });
    }

    if (!CLIENT_SECRET) {
      return NextResponse.json({ error: "Casdoor client secret not configured" }, { status: 500 });
    }

    // Exchange authorization code for tokens
    const REDIRECT_URI =
      process.env.NEXT_PUBLIC_CASDOOR_REDIRECT_URI ||
      "https://mobile2.falahos.my/mobile/auth/callback";

    const tokenRes = await fetch(CASDOOR_TOKEN_URL, {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams({
        grant_type: "authorization_code",
        client_id: CLIENT_ID,
        client_secret: CLIENT_SECRET,
        code,
        // redirect_uri must match exactly what was used in authorize request
        redirect_uri: REDIRECT_URI,
      }),
    });

    if (!tokenRes.ok) {
      const errBody = await tokenRes.text();
      console.error("[casdoor-oidc] Token exchange failed:", tokenRes.status, errBody);
      return NextResponse.json({ error: "Token exchange failed" }, { status: 502 });
    }

    const tokenData = await tokenRes.json();
    const accessToken = tokenData.access_token;
    const idToken = tokenData.id_token;

    if (!accessToken) {
      return NextResponse.json({ error: "No access_token in response" }, { status: 502 });
    }

    // Fetch userinfo from Casdoor
    const userRes = await fetch(CASDOOR_USERINFO_URL, {
      headers: { Authorization: `Bearer ${accessToken}` },
    });

    let userInfo = null;
    if (userRes.ok) {
      userInfo = await userRes.json();
    }

    return NextResponse.json({
      success: true,
      access_token: accessToken,
      id_token: idToken,
      token_type: tokenData.token_type || "Bearer",
      expires_in: tokenData.expires_in || 3600,
      refresh_token: tokenData.refresh_token || null,
      user: userInfo
        ? {
            id: userInfo.sub || userInfo.id,
            email: userInfo.email,
            name: userInfo.name || userInfo.displayName || userInfo.preferred_username,
            avatar: userInfo.avatar || userInfo.picture,
          }
        : null,
    });
  } catch (error) {
    console.error("[casdoor-oidc] Callback error:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
