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

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

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

  if (!existingUser.admin) return (
    <MainLayout currentPage="/jams/" title="Edit User" subtitle="Jams" backButton>
      <h1>Can't edit this user</h1>
      <p>You are not an admin</p>
    </MainLayout>
  );

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