
import { Conditional, ConditionalNull } from "@/components/utility/Conditional";
import { MainLayout } from "@/layout/MainLayout/MainLayout";
import { db } from "@/lib/mastoauth/kysely";
import { JSONContentTable, JSONJamTable, JSONJudgementTable } 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: {
    judgementid: 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 judgementid = params.judgementid;

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

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

  if (!existingUser.admin && editingJudgement.author_id != existingUser.id) return (
    <MainLayout currentPage="/jams/" title="Delete Judgement" subtitle="Jams" backButton>
      <h1>Can't delete this judgement</h1>
      <p>You did not publish this judgement</p>
    </MainLayout>
  );

  return (
    <MainLayout currentPage="/jams/" title="Delete Judgement" subtitle="Jams" backButton>
      <p>Deleting "<a href={`/jams/content/${editingJudgement.content_id}?until=${editingJudgement.published}`}>{editingJudgement.content}</a>"</p>
      <ConditionalNull condition={existingUser != null}>
        <p><small>Logged in as <b>{existingUser?.username}@{existingUser?.instance}</b></small></p>
      </ConditionalNull>
      <Form judgementID={editingJudgement.id} contentID={editingJudgement.content_id} />
    </MainLayout>
  )
}