import type { PrismaClient } from "@capakraken/db";
import {
  AllocationStatus,
  type FillDemandRequirementInput,
} from "@capakraken/shared";
import {
  createAssignment,
  type AssignmentWithRelations,
} from "./create-assignment.js";
import { applyDemandRequirementFillProgress } from "./apply-demand-requirement-fill-progress.js";

export interface DemandRequirementFillTarget {
  id: string;
  projectId: string;
  startDate: Date;
  endDate: Date;
  hoursPerDay: number;
  role: string | null;
  roleId: string | null;
  headcount: number;
  metadata: unknown;
}

export interface FillDemandRequirementWithLegacySyncResult {
  assignment: AssignmentWithRelations;
  updatedDemandRequirement: Awaited<
    ReturnType<typeof applyDemandRequirementFillProgress>
  >;
}

export async function fillDemandRequirementWithLegacySync(
  db: PrismaClient,
  demandRequirement: DemandRequirementFillTarget,
  input: FillDemandRequirementInput,
): Promise<FillDemandRequirementWithLegacySyncResult> {
  const hoursPerDay = input.hoursPerDay ?? demandRequirement.hoursPerDay;
  const percentage = Math.max(1, Math.min(100, Math.round((hoursPerDay / 8) * 100)));

  return db.$transaction(async (tx) => {
    const createdAssignment = await createAssignment(tx, {
      demandRequirementId: demandRequirement.id,
      resourceId: input.resourceId,
      projectId: demandRequirement.projectId,
      startDate: demandRequirement.startDate,
      endDate: demandRequirement.endDate,
      hoursPerDay,
      percentage,
      role: demandRequirement.role ?? undefined,
      roleId: demandRequirement.roleId ?? undefined,
      status: input.status ?? AllocationStatus.PROPOSED,
      metadata: (demandRequirement.metadata as Record<string, unknown> | null) ?? {},
    });

    const updatedDemandRequirement = await applyDemandRequirementFillProgress(tx, {
      demandRequirementId: demandRequirement.id,
      headcount: demandRequirement.headcount,
    });

    return {
      assignment: createdAssignment,
      updatedDemandRequirement,
    };
  });
}
