import { Link, type LoaderFunction } from "react-router-dom";
import { accountStore, type User } from "@/stores";
import { setCookie, CookieKeys } from "@/ui/Shared";

export const loader: LoaderFunction = () => {
  const sso = new URLSearchParams(location.search).get("sso");
  const user = sso ? getSSOUser(new URLSearchParams(atob(sso))) : undefined;
  if (user) {
    accountStore.login(user);
    setCookie(CookieKeys.USER, JSON.stringify(user));
  }
  return null;
};

export const Component: React.FC = () => (
  <>
    new match
    <Link to="/waitroom/1/2/3">waitroom</Link>
  </>
);
Component.displayName = "Match";

/** 从SSO跳转回的URL之中，解析用户信息 */
function getSSOUser(searchParams: URLSearchParams): User {
  return Object.fromEntries(searchParams) as unknown as User;
}
