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 { CheckIcon } from "lucide-react";

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

  try {
    // prisma function to get project by projectID if user is part of the project
    const features = await prisma.feature.findMany({
      where: {
        project_id: BigInt(projectID),
      },
    });

    return features;
  } catch (err) {
    console.error(err);
  }
}

export async function FeatureList({ projectID }: { projectID: string }) {
  const features = await fetchFeatures(projectID);
  return (
    <div>
      <div className="grid gap-4">
        {features?.map((feature) => (
          <div className="flex items-start gap-4" key={feature.id}>
            <CheckIcon className="w-6 h-6 text-green-500" />
            <div className="grid gap-1">
              <h3 className="font-semibold">{feature.name}</h3>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {feature.description}
              </p>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
