import "./page.scss";

import AuditTableClient from "./AuditTableClient";
import {
  AuditApiResponse,
  AuditQueryResult,
  DEFAULT_PAGE_SIZE,
  extractArray,
  normalizeRows,
  resolveTotal,
} from "./auditTransforms";
import { cookies } from "next/headers";
import {
  AUDIT_CACHE_TAG,
  AUTH_COOKIE_NAME,
  BE_BASE_URL,
  REVALIDATE_SECONDS,
} from "@/app/services/constants";

async function fetchInitialAudits(): Promise<AuditQueryResult> {
  const cookieStore = await cookies();
  const token = cookieStore.get(AUTH_COOKIE_NAME)?.value;

  if (!token) {
    throw new Error("Missing auth token");
  }

  const params = new URLSearchParams();
  params.set("limit", DEFAULT_PAGE_SIZE.toString());
  params.set("page", "1");

  const backendUrl = `${BE_BASE_URL}/api/v1/audit${
    params.size ? `?${params.toString()}` : ""
  }`;

  const response = await fetch(backendUrl, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    next: {
      revalidate: REVALIDATE_SECONDS,
      tags: [AUDIT_CACHE_TAG],
    },
  });

  if (!response.ok) {
    const errorData = await response
      .json()
      .catch(() => ({ message: "Failed to fetch audits" }));
    throw new Error(errorData?.message || "Failed to fetch audits");
  }

  const payload = (await response.json()) as AuditApiResponse;
  const rows = normalizeRows(extractArray(payload), 0);
  const total = resolveTotal(payload, rows.length);

  return {
    rows,
    total,
    payload,
    pageIndex: 0,
  };
}

export default async function AuditPage() {
  const initialData = await fetchInitialAudits();
  return <AuditTableClient initialData={initialData} />;
}
