import type { Prisma, PrismaClient } from "@capakraken/db";
import { buildSplitAllocationReadModel } from "./build-split-allocation-read-model.js";

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

export interface CountEstimateHandoffPlanningEntriesInput {
  projectId: string;
  estimateVersionId: string;
}

export async function countEstimateHandoffPlanningEntries(
  db: DbClient,
  input: CountEstimateHandoffPlanningEntriesInput,
): Promise<number> {
  const handoffWhere = {
    projectId: input.projectId,
    metadata: {
      path: ["estimateHandoff", "estimateVersionId"],
      equals: input.estimateVersionId,
    },
  } as const;

  const [demandRequirements, assignments] = await Promise.all([
    db.demandRequirement.findMany({
      where: handoffWhere,
      select: {
        id: true,

        projectId: true,
        startDate: true,
        endDate: true,
        hoursPerDay: true,
        percentage: true,
        role: true,
        roleId: true,
        headcount: true,
        status: true,
        metadata: true,
        createdAt: true,
        updatedAt: true,
      },
    }),
    db.assignment.findMany({
      where: handoffWhere,
      select: {
        id: true,

        demandRequirementId: true,
        resourceId: true,
        projectId: true,
        startDate: true,
        endDate: true,
        hoursPerDay: true,
        percentage: true,
        role: true,
        roleId: true,
        dailyCostCents: true,
        status: true,
        metadata: true,
        createdAt: true,
        updatedAt: true,
      },
    }),
  ]);

  return buildSplitAllocationReadModel({
    demandRequirements,
    assignments,
  }).allocations.length;
}
