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";

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,
}: {
  workspaceID: string;
  projectID: 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>
        ))
      ) : (
        <p>No features</p>
      )}
      <CreateFeature workspaceID={workspaceID} projectID={projectID} />
    </div>
  );
}
