import { Prisma } from "@prisma/client";
import { cache as reactCache } from "react";
import { prisma } from "@formbricks/database";
import { DatabaseError } from "@formbricks/types/errors";
import { TOrganizationProject } from "@/modules/organization/settings/api-keys/types/api-keys";

export const getProjectsByOrganizationId = reactCache(
  async (organizationId: string): Promise<TOrganizationProject[]> => {
    try {
      const projects = await prisma.project.findMany({
        where: {
          organizationId,
        },
        select: {
          id: true,
          environments: true,
          name: true,
        },
      });

      return projects;
    } catch (error) {
      if (error instanceof Prisma.PrismaClientKnownRequestError) {
        throw new DatabaseError(error.message);
      }

      throw error;
    }
  }
);
