import type { Metadata } from "next";
import { Suspense } from "react";
import { cacheLife, cacheTag } from "next/cache";
import { fetchQuery } from "convex/nextjs";

import { PublicAuditPage } from "@/components/public-audit/public-audit-page";
import { PublicAuditStatus } from "@/components/public-audit/public-audit-status";
import { api } from "@/convex/_generated/api";
import { publicAuditCacheTag } from "@/lib/audits/public-audit-cache";
import { toPublicAuditRenderState } from "@/lib/audits/public-audit-presenter";
import type { PublicAuditLookupResult } from "@/lib/audits/public-audit-types";
import { parsePublicAuditSlug } from "@/lib/audits/slugs";

export const metadata: Metadata = {
  title: "Website-Audit",
  robots: {
    index: false,
    follow: false,
    googleBot: {
      index: false,
      follow: false,
    },
  },
};

type PublicAuditRouteProps = {
  params: Promise<{ slug: string }>;
};

async function getCachedPublicAudit(slug: string): Promise<PublicAuditLookupResult> {
  "use cache";

  const normalizedSlug = parsePublicAuditSlug(slug);
  if (!normalizedSlug) {
    return null;
  }

  cacheTag(publicAuditCacheTag(normalizedSlug));
  cacheLife("days");

  return await fetchQuery(api.audits.getPublicBySlug, { slug: normalizedSlug });
}

async function PublicAuditContent({ params }: PublicAuditRouteProps) {
  const { slug } = await params;
  const result = await getCachedPublicAudit(slug);
  const renderState = toPublicAuditRenderState(result);

  if (renderState.kind === "pending") {
    return <PublicAuditStatus status="pending" />;
  }

  if (renderState.kind === "unavailable") {
    return <PublicAuditStatus status="unavailable" />;
  }

  return <PublicAuditPage audit={renderState.audit} />;
}

export default function PublicAuditRoute({ params }: PublicAuditRouteProps) {
  return (
    <Suspense fallback={<PublicAuditStatus status="pending" />}>
      <PublicAuditContent params={params} />
    </Suspense>
  );
}
