import type { Prisma, PrismaClient } from "@capakraken/db";
import { TRPCError } from "@trpc/server";
import type { AllocationEntryResolution } from "./load-allocation-entry.js";
import { deleteAssignment } from "./delete-assignment.js";
import { deleteDemandRequirement } from "./delete-demand-requirement.js";

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

export interface DeleteAllocationEntryResult {
  deletedId: string;
  projectId: string;
  resourceId: string | null;
  strategy: "explicit_demand" | "explicit_assignment";
}

export async function deleteAllocationEntry(
  db: DbClient,
  resolved: AllocationEntryResolution,
): Promise<DeleteAllocationEntryResult> {
  if (resolved.kind === "demand") {
    const result = await deleteDemandRequirement(
      db as Parameters<typeof deleteDemandRequirement>[0],
      resolved.demandRequirement.id,
    );

    return {
      deletedId: result.deletedId,
      projectId: result.projectId,
      resourceId: null,
      strategy: "explicit_demand",
    };
  }

  if (resolved.kind === "assignment") {
    const result = await deleteAssignment(
      db as Parameters<typeof deleteAssignment>[0],
      resolved.assignment.id,
    );

    return {
      deletedId: result.deletedId,
      projectId: result.projectId,
      resourceId: result.resourceId,
      strategy: "explicit_assignment",
    };
  }

  throw new TRPCError({ code: "NOT_FOUND", message: "Allocation not found" });
}
