import type {
  AllocationLike,
  AllocationReadModel,
  Assignment,
  DemandRequirement,
} from "@capakraken/shared";

function toDemandRequirement<TAllocation extends AllocationLike>(
  allocation: TAllocation,
): DemandRequirement<TAllocation> {
  return {
    ...allocation,
    kind: "demand",
    sourceAllocationId: allocation.entityId ?? allocation.id,
    resourceId: null,
    isPlaceholder: true,
    requestedHeadcount: allocation.headcount,
    unfilledHeadcount: allocation.headcount,
  };
}

function toAssignment<TAllocation extends AllocationLike>(
  allocation: TAllocation,
): Assignment<TAllocation> {
  return {
    ...allocation,
    kind: "assignment",
    sourceAllocationId: allocation.entityId ?? allocation.id,
    resourceId: allocation.resourceId as string,
    isPlaceholder: false,
  };
}

export function buildAllocationReadModel<TAllocation extends AllocationLike>(
  allocations: TAllocation[],
): AllocationReadModel<TAllocation> {
  const demands: DemandRequirement<TAllocation>[] = [];
  const assignments: Assignment<TAllocation>[] = [];

  for (const allocation of allocations) {
    if (allocation.isPlaceholder || allocation.resourceId === null) {
      demands.push(toDemandRequirement(allocation));
      continue;
    }

    assignments.push(toAssignment(allocation));
  }

  return {
    allocations,
    demands,
    assignments,
  };
}
