import { redirect } from "next/navigation";

import { getClientByClientId } from "@/lib/dto/client";
import { getCurrentUser } from "@/lib/session";
import { Authorizing } from "@/components/auth/authorizing";
import { ErrorCard } from "@/components/auth/error-card";

export interface AuthorizeParams {
  oauth: string;
  clientId: string;
  scope: string;
  redirectUri: string;
}

export default async function AuthorizePage({
  searchParams,
}: {
  searchParams: AuthorizeParams;
}) {
  const user = await getCurrentUser();
  if (!user?.id) {
    redirect("/login");
  }

  const client = await getClientByClientId(searchParams.clientId);
  if (!client) {
    return (
      <div className="flex min-h-screen items-center justify-center p-4">
        <ErrorCard
          title="应用不存在"
          description="您尝试访问的应用不存在或已被删除"
          redirectUri={searchParams.redirectUri}
          error="invalid_client"
          errorDescription="应用不存在"
        />
      </div>
    );
  }

  // 检查应用是否被禁用
  if (!client.enabled) {
    return (
      <div className="flex min-h-screen items-center justify-center p-4">
        <ErrorCard
          title="应用已禁用"
          description="此应用已被管理员禁用，暂时无法使用"
          redirectUri={searchParams.redirectUri}
          error="access_denied"
          errorDescription="此应用已被禁用"
        />
      </div>
    );
  }

  // 检查回调地址是否匹配
  if (client.redirectUri !== searchParams.redirectUri) {
    return (
      <div className="flex min-h-screen items-center justify-center p-4">
        <ErrorCard
          title="回调地址不匹配"
          description="应用提供的回调地址与注册时不符"
          redirectUri={searchParams.redirectUri}
          error="invalid_request"
          errorDescription="回调地址不匹配"
        />
      </div>
    );
  }

  return (
    <div className="flex min-h-screen items-center justify-center p-4">
      <Authorizing {...searchParams} />
    </div>
  );
}
