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 { CreateFeature } from "@/components/create-feature";
import { GenerateProject } from "@/components/generate-project";

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

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

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

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

  if (!features) return undefined;

  const res = features.map((feature) => ({
    ...feature,
    id: String(feature.id),
    project_id: String(feature.project_id),
  }));

  return res;
}

export async function FeatureList({
  workspaceID,
  projectID,
  project_name,
  project_description,
  tech_stack,
}: {
  workspaceID: string;
  projectID: string;
  project_name: string;
  project_description: string;
  tech_stack: string[];
}) {
  const features = await fetchFeatures(projectID);
  return (
    <div>
      <h1 className="font-bold">Feature List</h1>
      {features?.length != 0 ? (
        features?.map((feature) => (
          <div key={feature.id}>
            {feature.name} - {feature.description}
          </div>
        ))
      ) : (
        <h1>No features yet.</h1>
      )}
      <CreateFeature workspaceID={workspaceID} projectID={projectID} />
      <GenerateProject
        workspaceID={workspaceID}
        projectID={projectID}
        project_name={project_name}
        project_description={project_description}
        tech_stack={tech_stack}
      />
    </div>
  );
}
