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 { CreateWorkspace } from "@/components/create-workspace";

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

async function fetchWorkspaces() {
  const supabase = createServerComponentClient<Database>({ cookies });
  const session = await getSession(supabase);

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

  const workspaces = await prisma.profile.findUnique({
    where: {
      id: session.user.id,
    },
    include: {
      profile_workspace: {
        include: {
          workspace: true,
        },
      },
    },
  });

  if (!workspaces) return undefined;

  const res = workspaces.profile_workspace.map((relation) => ({
    ...relation.workspace,
    id: String(relation.workspace.id),
  }));

  return res;
}

export async function WorkspacesSidebar() {
  const workspaces = await fetchWorkspaces();
  return (
    <div>
      <h1>Workspaces Sidebar</h1>
      {workspaces ? (
        workspaces.map((workspace) => (
          <div key={workspace.id}>
            <Link href={`/w/${workspace.id}`}>{workspace.name}</Link>
          </div>
        ))
      ) : (
        <p>No workspaces</p>
      )}
      <CreateWorkspace />
    </div>
  );
}
