import type { Metadata } from 'next';
import { cookies } from 'next/headers';
import { notFound } from 'next/navigation';

import { getPuzzle } from '@/lib/puzzles';

import Puzzle from '@/components/ui/Puzzle';
import SWRFallback from '@/components/ui/SWRFallback';

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 ? 'Puzzle introuvable' : puzzle.name
  };
}

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

  if (!token) {
    notFound();
  }

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

  if (!puzzle) {
    notFound();
  }

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