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";
import { CreateTask } from "@/components/create-task";
import GenerateTasks from "./generate-tasks";

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

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

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

  const tasks = await prisma.task.findMany({
    where: {
      project_id: BigInt(projectID),
    },
  });

  if (!tasks) return undefined;

  const res = tasks.map((task) => ({
    ...task,
    id: String(task.id),
    project_id: String(task.project_id),
    feature_id: String(task.feature_id),
  }));

  return res;
}

export async function TaskList({
  workspaceID,
  projectID,
}: {
  workspaceID: string;
  projectID: string;
}) {
  const tasks = await fetchTasks(projectID);
  return (
    <div>
      <h1 className="font-bold">Task List</h1>
      {tasks?.length != 0 ? (
        tasks?.map((task) => (
          <div key={task.id}>
            {task.name} - {task.description}
          </div>
        ))
      ) : (
        <p>No tasks</p>
      )}
      <CreateTask workspaceID={workspaceID} projectID={projectID} />
      <GenerateTasks stack={["Next.js", "Supabase"]} />
    </div>
  );
}
