import { getPuzzle } from '@/lib/puzzles';
import { getURL } from '@/lib/utils';
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 });

  if (!puzzle) {
    notFound();
  }

  return {
    title: puzzle.name,
    openGraph: {
      title: puzzle.name,
      type: 'website',
      url: getURL(`/dashboard/puzzles/${puzzle.id}`)
      // IMAGES WITH OG IMAGE
    },
    twitter: {
      title: 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>
  );
}
