import type { Prisma, PrismaClient } from "@capakraken/db";

type DbClient =
  | Pick<PrismaClient, "demandRequirement" | "assignment">
  | Pick<Prisma.TransactionClient, "demandRequirement" | "assignment">;

export interface DeleteDemandRequirementResult {
  deletedId: string;
  projectId: string;
}

export async function deleteDemandRequirement(
  db: DbClient,
  id: string,
): Promise<DeleteDemandRequirementResult> {
  const demandRequirement = await db.demandRequirement.findUnique({
    where: { id },
    select: {
      id: true,
      projectId: true,
    },
  });

  if (!demandRequirement) {
    throw new Error("Demand requirement not found");
  }

  await db.assignment.updateMany({
    where: { demandRequirementId: demandRequirement.id },
    data: { demandRequirementId: null },
  });
  await db.demandRequirement.delete({
    where: { id: demandRequirement.id },
  });

  return {
    deletedId: demandRequirement.id,
    projectId: demandRequirement.projectId,
  };
}
