import { redirect } from "next/navigation";
import { AuthLoginPanel } from "@/components/auth-login-panel";
import { getAuthRuntimeConfig, safeNextPath } from "@/lib/auth/config";
import { getOptionalAuthSession } from "@/lib/server/auth/current-user";

const errorMessages: Record<string, string> = {
  auth_not_configured: "认证配置不完整，请先在服务器环境变量中配置 SSO。",
  callback_failed: "登录回调处理失败，请重新登录。",
  state_invalid: "登录状态已失效，请重新登录。"
};

export default async function LoginPage({
  searchParams
}: {
  searchParams?: Promise<Record<string, string | string[] | undefined>>;
}) {
  const params = await searchParams;
  const next = safeNextPath(singleParam(params?.next));
  const session = await getOptionalAuthSession();
  if (session) redirect(next);

  const config = getAuthRuntimeConfig();
  const errorCode = singleParam(params?.error);
  const message = errorCode ? errorMessages[errorCode] || "登录失败，请重新登录。" : null;

  return (
    <AuthLoginPanel
      next={next}
      configured={config.configured}
      message={message}
      missing={!config.configured && config.required ? config.missing : []}
    />
  );
}

function singleParam(value: string | string[] | undefined): string | undefined {
  return Array.isArray(value) ? value[0] : value;
}
