import { type ActionFunctionArgs, json } from "@remix-run/node";
import { OAuthClient } from "~/api/login/oauth-client";
import { getServerOAuthConfigRuntime } from "~/config/oauth-secret.server";

/**
 * 这个Action作为获取用户信息的服务器端代理。
 * 它接收来自前端的`access_token`，然后在后端安全地获取用户信息。
 */
export async function action({ request }: ActionFunctionArgs) {
  if (request.method !== "POST") {
    return json({ success: false, error: "Method Not Allowed" }, { status: 405 });
  }

  try {
    const { accessToken } = await request.json();

    if (!accessToken || typeof accessToken !== 'string') {
      return json({ success: false, error: "Missing or invalid 'accessToken' in request body" }, { status: 400 });
    }

    console.log("🔧 [/api/oauth/userinfo] 收到代理请求。");

    // 🔒 安全：从 .server.ts 文件运行时读取配置
    const oauthClient = new OAuthClient(getServerOAuthConfigRuntime());
    const userInfoResponse = await oauthClient.getUserInfo(accessToken);

    if (!userInfoResponse || !userInfoResponse.success) {
      console.error("❌ [/api/oauth/userinfo] 从IDaaS获取用户信息失败。");
      return json({ success: false, error: "Failed to get user info from IDaaS" }, { status: 502 });
    }

    console.log("✅ [/api/oauth/userinfo] 已通过代理成功获取用户信息。");
    
    return json({ success: true, data: userInfoResponse.data });

  } catch (error) {
    console.error("❌ [/api/oauth/userinfo] 代理API发生意外错误:", error);
    const errorMessage = error instanceof Error ? error.message : "An unknown error occurred.";
    return json({ success: false, error: "Proxy internal error", details: errorMessage }, { status: 500 });
  }
} 