import "./page.scss";

import AuditTableClient from "./AuditTableClient";
import { DEFAULT_PAGE_SIZE } from "./auditTransforms";
import { fetchAudits } from "@/app/services/audits";
import {
  ENTITY_PREFIX,
  PAGE_SIZE_OPTIONS,
} from "@/app/dashboard/audits/auditConstants";

type AuditPageProps = {
  searchParams?: Promise<Record<string, string | string[] | undefined>>;
};

const toSingleValue = (value?: string | string[]): string | undefined => {
  if (Array.isArray(value)) return value[0];
  return value;
};

const clampNumber = (value: number, min: number, max?: number) => {
  if (Number.isNaN(value)) return min;
  if (value < min) return min;
  if (typeof max === "number" && value > max) return max;
  return value;
};

export default async function AuditPage({ searchParams }: AuditPageProps) {
  const params = searchParams ? await searchParams : {};
  const pageParam = toSingleValue(params?.page);
  const limitParam = toSingleValue(params?.limit);
  const sortParam = toSingleValue(params?.sort) || undefined;
  const entityQuery = toSingleValue(params?.entity)?.trim() || "";

  const page = clampNumber(parseInt(pageParam || "1", 10), 1);
  const parsedLimit = parseInt(limitParam || String(DEFAULT_PAGE_SIZE), 10);
  const limit =
    PAGE_SIZE_OPTIONS.find(size => size === parsedLimit) ?? DEFAULT_PAGE_SIZE;

  const data = await fetchAudits({
    limit,
    page,
    sort: sortParam,
    entity: entityQuery ? `${ENTITY_PREFIX}${entityQuery}` : undefined,
  });

  return (
    <AuditTableClient
      rows={data.rows}
      total={data.total ?? data.rows.length}
      pageIndex={data.pageIndex}
      pageSize={limit}
      sortParam={sortParam}
      entityQuery={entityQuery}
    />
  );
}
