import { getPuzzle } from '@/lib/puzzles';
import Puzzle from '@/ui/Puzzle';
import SWRFallback from '@/ui/SWRFallback';
import type { Metadata } from 'next';
import { cookies } from 'next/headers';
import { notFound } from 'next/navigation';

export async function generateMetadata({ params }: { params: { id: number } }): Promise<Metadata> {
  const { id } = params;
  const token = cookies().get('token')?.value;

  if (!token) {
    notFound();
  }

  const puzzle = await getPuzzle({ token, id });

  return { title: `${puzzle.name} - Peer-at Code` };
}

export default async function Page({ params: { id } }: { params: { id: number } }) {
  const token = cookies().get('token')?.value;

  if (!token) {
    notFound();
  }

  const puzzle = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/puzzle/${id}`, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  }).then((res) => res.json());

  if (!puzzle) {
    notFound();
  }

  return (
    <SWRFallback fallback={{ [`puzzles/${puzzle.id}`]: puzzle }}>
      <Puzzle token={token} id={id} />
    </SWRFallback>
  );
}
