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

export async function loader({ request }: LoaderFunctionArgs) {
  const session = await sessionStorage.getSession(request.headers.get("Cookie"));

  // 获取访问令牌和用户角色
  const accessToken = session.get("accessToken");
  const userRole = session.get("userRole");

  // 🔑 只有非 admin 用户才需要调用 IDaaS 单点登出
  const isAdmin = userRole === 'admin';

  if (accessToken && !isAdmin) {
    try {
      // 🔒 安全：使用服务器端专用函数获取完整配置
      const oauthClient = new OAuthClient(getServerOAuthConfigRuntime());

      // 构建登出后重定向URL
      const url = new URL(request.url);
      const redirectUrl = url.searchParams.get("redirect") || `${url.protocol}//${url.host}/login`;

      // 调用IDaaS单点登出
      const logoutSuccess = await oauthClient.logout(accessToken, redirectUrl);

      if (!logoutSuccess) {
        console.warn("IDaaS单点登出失败，但仍清除本地会话");
      }
    } catch (error) {
      console.error("单点登出过程中出错:", error);
    }
  } else if (isAdmin) {
    console.log("admin 用户登出，跳过 IDaaS 单点登出");
  }

  // 无论IDaaS登出是否成功，都清除本地会话
  const cookie = await sessionStorage.destroySession(session);

  return redirect("/login", {
    headers: {
      "Set-Cookie": cookie
    }
  });
}

export default function Logout() {
  return (
    <div className="flex items-center justify-center min-h-screen">
      <div className="text-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
        <p className="mt-4 text-gray-600">正在退出登录...</p>
      </div>
    </div>
  );
}