import { ReactElement } from "react";
import { ActionMenu } from "@/app/components/action-menu";
import { Metadata } from "next";
import moment from "moment";
import { notFound } from "next/navigation";
import { CodeBlock } from "@/app/components/codeBlock";

type PasteProps = {
  params: {
    id: string;
  };
};

type Paste = {
  /**
   * The paste content.
   */
  content: string;

  /**
   * The date the paste was created.
   */
  created: number;
};

export async function generateMetadata({
  params: { id },
}: PasteProps): Promise<Metadata> {
  const data: Paste | undefined = await getData(id);
  if (data == undefined) {
    return {
      description: "Not found",
    };
  }

  return {
    title: `Paste - ${id}`,
    description: `Created: ${moment(data.created)}\n\nClick to view the paste.`,
  };
}

async function getData(id: string): Promise<Paste | undefined> {
  const response: Response = await fetch(
    `${process.env.NEXT_PUBLIC_API_ENDPOINT}/${id}`,
    {
      next: {
        revalidate: 300, // Keep this response cached for 5 minutes
      },
    },
  );
  const json = await response.json();

  if (json.code && json.message) {
    return undefined;
  }
  return json as Paste;
}

export default async function Paste({
  params: { id },
}: PasteProps): Promise<ReactElement> {
  const data: Paste | undefined = await getData(id);

  if (data == undefined) {
    return notFound();
  }

  return (
    <div className="relative">
      <ActionMenu />

      <div className="p-1 hljs !bg-transparent text-sm">
        <CodeBlock code={data.content} />
      </div>
    </div>
  );
}
