import { createServerComponentClient } from "@supabase/auth-helpers-nextjs";
import { Database } from "@/types/supabase";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { CreateProject } from "@/components/create-project";

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

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

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

  const projects = await prisma.project.findMany({
    where: {
      workspace_id: BigInt(workspaceID),
      profile_project: {
        some: {
          profile_id: session.user.id,
        },
      },
    },
  });

  if (!projects) return undefined;

  const res = projects.map((project) => ({
    ...project,
    id: String(project.id),
    workspace_id: String(project.workspace_id),
  }));

  return res;
}

export async function Sidebar({ workspaceID }: { workspaceID: string }) {
  const projects = await fetchProjects(workspaceID);
  return (
    <div>
      <h1>Sidebar</h1>
      {projects?.length != 0 ? (
        projects?.map((project) => (
          <div key={project.id}>
            <Link href={`/w/${workspaceID}/p/${project.id}`}>
              {project.name}
            </Link>
          </div>
        ))
      ) : (
        <p>No projects</p>
      )}
      <CreateProject workspaceID={workspaceID} />
    </div>
  );
}
