import type { Metadata } from "next";
import { peekPasswordResetToken } from "@/lib/auth/accounts";
import { isDatabaseAvailable } from "@/lib/db";
import { AuthLayout } from "@/components/auth/AuthLayout";
import { ResetPasswordForm } from "@/components/auth/ResetPasswordForm";
import { ResetLinkProblem, type ResetLinkIssue } from "@/components/auth/ResetLinkProblem";

export const metadata: Metadata = {
  title: "Set a new password | ScanReceipts",
  robots: { index: false, follow: false },
};

/** Token state changes per request, so this page must never be cached. */
export const dynamic = "force-dynamic";

/**
 * Target of the emailed reset link.
 *
 * Validates the token server-side *without* spending it, so an expired or
 * already-used link says so immediately instead of after the user has typed a
 * new password into a form that was never going to work.
 */
export default async function ResetPasswordPage({
  searchParams,
}: {
  searchParams: Promise<{ token?: string | string[] }>;
}) {
  const params = await searchParams;
  const token = Array.isArray(params.token) ? params.token[0] : params.token;

  let issue: ResetLinkIssue | null = null;

  if (!token) {
    issue = "invalid";
  } else if (!(await isDatabaseAvailable())) {
    issue = "unavailable";
  } else {
    const state = await peekPasswordResetToken(token);
    if (state === "expired") issue = "expired";
    else if (state === "invalid") issue = "invalid";
  }

  return (
    <AuthLayout>
      {issue ? <ResetLinkProblem issue={issue} /> : <ResetPasswordForm token={token as string} />}
    </AuthLayout>
  );
}
