import { customerApi } from "@/lib/api/customer";
import { requireServerToken } from "@/lib/auth/server";
import type { ApiCreditRequest } from "@/lib/api/types";
import CreditRequestForm from "@/components/dashboard/CreditRequestForm";

type PageProps = {
  params: Promise<{ id: string }>;
};

async function loadCreditRequest(token: string, id: number) {
  try {
    return { data: await customerApi.creditRequest(token, id), error: null as string | null };
  } catch (e) {
    return { data: null as ApiCreditRequest | null, error: (e as Error).message };
  }
}

/**
 * The form itself is genuinely interactive and stays a client component, but the
 * record it edits does not have to be fetched by the browser. Previously the
 * page rendered a spinner, waited for hydration so `useToken` could read the
 * auth cookie, then fetched — the form could not appear until that whole chain
 * completed. Fetching during SSR hands the form its initial values immediately.
 */
export default async function EditCreditRequestPage({ params }: PageProps) {
  const { id } = await params;
  const token = await requireServerToken(`/credit-request/${id}/edit`);

  const { data, error: err } = await loadCreditRequest(token, Number(id));

  if (err) return <div className="rounded-xl bg-red-50 p-6 text-red-700 ring-1 ring-red-100">{err}</div>;
  if (!data) return null;

  return <CreditRequestForm existing={data} />;
}
