
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 editingContent = await db
    .selectFrom('content')
    .where('content.id', '=', contentid)
    .selectAll()
    .executeTakeFirst() as unknown as JSONContentTable;

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

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

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