import type { StructureMasterDetails, StructureMasterRow } from "../_components/schema";
import { StructureCreateForm } from "../_components/structure-form";
import { fetchBackendStructureMaster } from "../_lib/structure-master-server-api";

type PageProps = {
  searchParams: Promise<{ id?: string; ISIN?: string }>;
};

export default async function StructureMasterCreatePage({ searchParams }: PageProps) {
  const { id, ISIN } = await searchParams;
  const recordId = id?.trim() ? Number.parseInt(id, 10) : undefined;
  const validId = recordId !== undefined && !Number.isNaN(recordId) ? recordId : undefined;
  const prefillIsin = ISIN?.trim() || undefined;
  const formKey = validId ? String(validId) : prefillIsin ?? "new";

  let initialRecord: { row: StructureMasterRow; details?: StructureMasterDetails } | undefined;
  let loadError: string | undefined;

  if (validId) {
    const { rows, detailsById, errorMessage } = await fetchBackendStructureMaster({
      id: validId,
      page: 1,
      pageSize: 1,
    });
    const row = rows.find((item) => item.id === validId);

    if (row) {
      initialRecord = { row, details: detailsById[validId] };
    } else {
      loadError =
        errorMessage ?? `Could not find a structure master record for ID ${validId}.`;
    }
  }

  return (
    <StructureCreateForm
      key={formKey}
      recordId={validId}
      prefillIsin={validId ? undefined : prefillIsin}
      initialRecord={initialRecord}
      loadError={loadError}
    />
  );
}
