
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: {
    jamid: 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 jamid = params.jamid;

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

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

  if (!existingUser.admin && editingJam.author_id != existingUser.id) return (
    <MainLayout currentPage="/jams/" title="Edit Jam" subtitle="Jams" backButton>
      <h1>Can't edit this Jam</h1>
      <p>You do not own this Jam</p>
    </MainLayout>
  );

  return (
    <MainLayout currentPage="/jams/" title="Edit Jam" subtitle="Jams" backButton>
      <p>Editing <a href={`/jams/content/${editingJam.id}`}>{editingJam.name}</a></p>
      <ConditionalNull condition={existingUser != null}>
        <p><small>Logged in as <b>{existingUser?.username}@{existingUser?.instance}</b></small></p>
      </ConditionalNull>
      <Form jamID={editingJam.id} preset={editingJam} />
    </MainLayout>
  )
}