import { Sidebar } from "@/components/sidebar";
import { createServerComponentClient } from "@supabase/auth-helpers-nextjs";
import { Database } from "@/types/supabase";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/prisma";

async function getSession(supabase: any) {
  const {
    data: { session },
  } = await supabase.auth.getSession();
  return session;
}

async function getWorkspace(workspaceID: string) {
  const supabase = createServerComponentClient<Database>({ cookies });
  const session = await getSession(supabase);

  if (!session) redirect("/auth");

  try {
    const workspace = await prisma.workspace.findUnique({
      where: {
        id: BigInt(workspaceID),
      },
    });

    if (!workspace) return undefined;

    const res = {
      ...workspace,
      id: String(workspace.id),
    };

    return res;
  } catch (err) {
    console.error(err);
    return;
  }
}
export default async function Workspace({
  params: { workspaceID },
}: {
  params: { workspaceID: string };
}) {
  const workspace = await getWorkspace(workspaceID);
  const supabase = createServerComponentClient<Database>({ cookies });
  const session = await getSession(supabase);

  if (!workspace)
    return (
      <div className="flex h-screen">
        <h1 className="m-auto">Workspace not found.</h1>
      </div>
    );

  if (
    !(await prisma.profile_workspace.findFirst({
      where: {
        profile_id: session.user.id,
        workspace_id: BigInt(workspaceID),
      },
    }))
  ) {
    return (
      <div className="flex h-screen">
        <h1 className="m-auto">You are not a member of this workspace.</h1>
      </div>
    );
  }

  return (
    <div>
      <h1>Workspace: {workspaceID}</h1>
      <Sidebar workspaceID={workspaceID} />
    </div>
  );
}
