
import { Conditional, ConditionalNull } from "@/components/utility/Conditional";
import { MainLayout } from "@/layout/MainLayout/MainLayout";
import { db } from "@/lib/mastoauth/kysely";
import { JSONContentTable, JSONJamTable } from "@/lib/mastoauth/realtypes";
import { cookies } from "next/headers";
import { notFound, redirect } from "next/navigation";
import { Form } from "./components/form";

export default async function Home({
  params
}: {
  params: {
    contentid: string
  }
}) {
  const cookieStore = cookies();
  const token = cookieStore.get('token')?.value;
  let existingUser;
  if (token != null) {
    let existingToken = await db
      .selectFrom('tokens')
      .where('tokens.id', '=', token)
      .select('owner')
      .executeTakeFirst();

    if (existingToken != null) {
      existingUser = await db
        .selectFrom('users')
        .where('users.id', '=', existingToken.owner)
        .selectAll()
        .executeTakeFirst();
    }
  }

  if (existingUser == null) return redirect("/jams/");

  const contentid = params.contentid;

  if (contentid == null) return notFound();
  
  // It's a JSONJamTable. I don't know why TS hates `number` => `string` conversion.
  let parentContent = await db
    .selectFrom('content')
    .where('content.id', '=', contentid)
    .selectAll()
    .executeTakeFirst() as unknown as JSONContentTable;

  if (parentContent == null) return notFound();

  return (
    <MainLayout currentPage="/jams/" title="New Submission" subtitle="Jams" backButton>
      <p>Judge <a href={`/jams/content/${parentContent.id}`}>{parentContent.name}</a></p>
      <ConditionalNull condition={existingUser != null}>
        <p><small>Logged in as <b>{existingUser?.username}@{existingUser?.instance}</b></small></p>
      </ConditionalNull>
      <Form contentID={parentContent.id} />
    </MainLayout>
  )
}