import { redirect } from "next/navigation";
import { sql } from "drizzle-orm";
import { getDb, schema } from "@/db";
import { getCtx } from "@/lib/auth";
import { AuthFrame, LoginForm } from "@/components/auth-forms";

export const dynamic = "force-dynamic";
export const metadata = { title: "Sign in" };

export default async function Login({ searchParams }: { searchParams: Promise<{ error?: string; reset?: string; signedup?: string }> }) {
  const db = await getDb();
  const [{ n }] = (await db.select({ n: sql<number>`count(*)::int` }).from(schema.users)) as [{ n: number }];
  if (n === 0) redirect("/setup");
  if (await getCtx()) redirect("/dashboard");
  const sp = await searchParams;
  return <AuthFrame title="Welcome back" subtitle="Sign in to your workspace to continue"><LoginForm error={sp.error} google={!!process.env.GOOGLE_CLIENT_ID} notice={sp.reset ? "Password changed. Sign in with your new password." : undefined} /></AuthFrame>;
}
