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

type DbClient = PrismaClient | Prisma.TransactionClient;

export interface DemandRequirementFillProgressInput {
  demandRequirementId: string;
  headcount: number;
}

export const UPDATED_DEMAND_REQUIREMENT_SELECT = {
  id: true,
  projectId: true,
  headcount: true,
  status: true,
} as const;

export async function applyDemandRequirementFillProgress(
  db: DbClient,
  input: DemandRequirementFillProgressInput,
) {
  const updatedDemandRequirement = await db.demandRequirement.update({
    where: { id: input.demandRequirementId },
    data:
      input.headcount > 1
        ? { headcount: input.headcount - 1 }
        : { status: AllocationStatus.COMPLETED },
    select: UPDATED_DEMAND_REQUIREMENT_SELECT,
  });

  return {
    ...updatedDemandRequirement,
    status: updatedDemandRequirement.status as AllocationStatus,
  };
}
