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

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

export interface DeleteAssignmentResult {
  deletedId: string;
  projectId: string;
  resourceId: string;
  reopenedDemandId: string | null;
}

export async function deleteAssignment(
  db: DbClient,
  id: string,
): Promise<DeleteAssignmentResult> {
  const assignment = await db.assignment.findUnique({
    where: { id },
    select: {
      id: true,
      projectId: true,
      resourceId: true,
      demandRequirementId: true,
    },
  });

  if (!assignment) {
    throw new Error("Assignment not found");
  }

  await db.assignment.delete({
    where: { id: assignment.id },
  });

  // Reverse demand fill progress: re-open the demand if the assignment was linked
  let reopenedDemandId: string | null = null;
  if (assignment.demandRequirementId) {
    const demand = await db.demandRequirement.findUnique({
      where: { id: assignment.demandRequirementId },
      select: { id: true, headcount: true, status: true },
    });

    if (demand) {
      const wasCompleted = demand.status === AllocationStatus.COMPLETED;
      await db.demandRequirement.update({
        where: { id: demand.id },
        data: {
          headcount: wasCompleted ? 1 : demand.headcount + 1,
          status: AllocationStatus.ACTIVE,
        },
      });
      reopenedDemandId = demand.id;
    }
  }

  return {
    deletedId: assignment.id,
    projectId: assignment.projectId,
    resourceId: assignment.resourceId,
    reopenedDemandId,
  };
}
