import { notFound } from "next/navigation";

import { CustomerPageShell } from "@/app/customer/_components/customer-page-shell";
import { StockAccumulatorScheduleView } from "@/app/customer/[tenant]/stock-accumulator/_components/stock-accumulator-schedule-view";
import {
  fetchCustomerStockAccumulatorView,
  type AccumulatorScheduleMode,
} from "@/app/customer/[tenant]/stock-accumulator/_lib/stock-accumulator-server-api";
import { isCustomerRecordId } from "@/app/customer/_lib/resolve-customer-record-id";
import { customerUrl } from "@/lib/tenant";

type PageProps = {
  params: Promise<{ tenant: string; id: string }>;
  searchParams: Promise<{ mode?: string; from?: string }>;
};

export default async function CustomerStockAccumulatorViewPage({ params, searchParams }: PageProps) {
  const { tenant, id: idParam } = await params;
  const { mode: modeParam, from } = await searchParams;
  const id = decodeURIComponent(idParam ?? "").trim();
  if (!id || !isCustomerRecordId(id)) {
    notFound();
  }

  const mode: AccumulatorScheduleMode =
    String(modeParam ?? "").toLowerCase() === "advance" ? "advance" : "table";

  const view = await fetchCustomerStockAccumulatorView(tenant, id, mode);
  const backHref =
    from === "cashflow"
      ? customerUrl(tenant, "/reports/cashflow")
      : from === "accumulator-report"
        ? customerUrl(tenant, "/reports/accumulator-report")
        : customerUrl(tenant, "/transactions");

  return (
    <CustomerPageShell>
      <StockAccumulatorScheduleView tenant={tenant} id={id} view={view} backHref={backHref} />
    </CustomerPageShell>
  );
}
