import type { PrismaClient } from "@prisma/client";

import { rosterRoleIsTrackedMember } from "./traineeRoster.js";



export type ProviderContractRow = {

  projectId: bigint;

  trainingProviderId: bigint;

  contractTarget: number;

  effectiveFrom: Date | null;

  notes: string | null;

};



const DEFAULT_OVERENROLLMENT_PERCENT = 15;



export function maxAllowedRegistration(contractTarget: number, maxOverenrollmentPercent: number): number {

  const pct = Math.max(0, Number(maxOverenrollmentPercent));

  const target = Math.max(0, Math.floor(contractTarget));

  return Math.floor(target * (1 + pct / 100));

}



export async function getProjectMaxOverenrollmentPercent(

  db: PrismaClient,

  projectId: bigint,

): Promise<number> {

  const row = await db.project.findUnique({

    where: { id: projectId },

    select: { maxOverenrollmentPercent: true },

  });

  if (!row) return DEFAULT_OVERENROLLMENT_PERCENT;

  return Number(row.maxOverenrollmentPercent);

}



export function effectiveContractNumerator(actual: number, contractTarget: number): number {

  const a = Math.max(0, Math.floor(actual));

  const t = Math.max(0, Math.floor(contractTarget));

  if (t <= 0) return 0;

  return Math.min(a, t);

}



/**

 * Dropouts among over-enrollment buffer (registered above contract target) do not count toward KPI.

 * Example: target 1040, registered 1100, 30 dropouts → effective 0 (buffer 60 absorbs them).

 * 90 dropouts → effective 30 (90 - 60), then capped at contract target for the rate denominator.

 */

export function effectiveDropoutNumerator(

  actualDropouts: number,

  registeredTrainees: number,

  contractTarget: number,

): number {

  const actual = Math.max(0, Math.floor(actualDropouts));

  const registered = Math.max(0, Math.floor(registeredTrainees));

  const target = Math.max(0, Math.floor(contractTarget));

  const overEnrollmentBuffer = Math.max(0, registered - target);

  const countingTowardTarget = Math.max(0, actual - overEnrollmentBuffer);

  if (target <= 0) return countingTowardTarget;

  return Math.min(countingTowardTarget, target);

}



export type VarCountsLike = { project: number; byTp: Map<string, number> };



export function applyDropoutBufferToCounts(

  actualDropouts: VarCountsLike,

  registered: VarCountsLike,

  contractByTp: Map<string, number>,

): VarCountsLike {

  const byTp = new Map<string, number>();

  let project = 0;

  const keys = new Set([...actualDropouts.byTp.keys(), ...registered.byTp.keys(), ...contractByTp.keys()]);

  for (const tpId of keys) {

    const effective = effectiveDropoutNumerator(

      actualDropouts.byTp.get(tpId) ?? 0,

      registered.byTp.get(tpId) ?? 0,

      contractByTp.get(tpId) ?? 0,

    );

    byTp.set(tpId, effective);

    project += effective;

  }

  return { project, byTp };

}



export async function getProviderContract(

  db: PrismaClient,

  projectId: bigint,

  trainingProviderId: bigint,

): Promise<ProviderContractRow | null> {

  const row = await db.trainingProviderContract.findFirst({

    where: { projectId, trainingProviderId },

    select: {

      projectId: true,

      trainingProviderId: true,

      contractTarget: true,

      effectiveFrom: true,

      notes: true,

    },

  });

  if (!row) return null;

  return {

    projectId: row.projectId,

    trainingProviderId: row.trainingProviderId,

    contractTarget: row.contractTarget,

    effectiveFrom: row.effectiveFrom,

    notes: row.notes,

  };

}



export async function countRegisteredTrainees(

  db: PrismaClient,

  projectId: bigint,

  trainingProviderId: bigint,

): Promise<number> {

  const rows = await db.trainee.groupBy({

    by: ["rosterRole"],

    where: { projectId, trainingProviderId },

    _count: { _all: true },

  });

  let total = 0;

  for (const r of rows) {

    if (rosterRoleIsTrackedMember(r.rosterRole)) total += r._count._all;

  }

  return total;

}



export async function assertCanRegisterTrainees(

  db: PrismaClient,

  projectId: bigint,

  trainingProviderId: bigint,

  additionalCount: number,

): Promise<void> {

  const contract = await getProviderContract(db, projectId, trainingProviderId);

  if (!contract) {

    throw Object.assign(

      new Error(

        "Provider contract target is not configured. Set the contractual trainee target on your provider profile before registering trainees.",

      ),

      { status: 422, code: "contract_not_configured" },

    );

  }

  const maxOverPct = await getProjectMaxOverenrollmentPercent(db, projectId);

  const registered = await countRegisteredTrainees(db, projectId, trainingProviderId);

  const maxAllowed = maxAllowedRegistration(contract.contractTarget, maxOverPct);

  const next = registered + Math.max(0, additionalCount);

  if (next > maxAllowed) {

    throw Object.assign(

      new Error(

        `Registration cap exceeded: ${next} would exceed maximum allowed ${maxAllowed} ` +

          `(contract ${contract.contractTarget} + ${maxOverPct}% over-enrollment). ` +

          `Currently registered: ${registered}.`,

      ),

      { status: 422, code: "registration_cap_exceeded" },

    );

  }

}



/** Contract targets per TP for KPI denominator resolution. */

export async function contractTargetsByTp(

  db: PrismaClient,

  projectId: bigint,

): Promise<Map<string, number>> {

  const rows = await db.trainingProviderContract.findMany({

    where: { projectId },

    select: { trainingProviderId: true, contractTarget: true },

  });

  const map = new Map<string, number>();

  for (const r of rows) {

    map.set(r.trainingProviderId.toString(), r.contractTarget);

  }

  return map;

}

/** Registered trainees (active + reserve) per provider for dropout buffer and caps. */
export async function registeredTraineesByTp(
  db: PrismaClient,
  projectId: bigint,
): Promise<Map<string, number>> {
  const rows = await db.trainee.groupBy({
    by: ["trainingProviderId", "rosterRole"],
    where: { projectId },
    _count: { _all: true },
  });
  const map = new Map<string, number>();
  for (const r of rows) {
    if (!rosterRoleIsTrackedMember(r.rosterRole)) continue;
    const id = r.trainingProviderId.toString();
    map.set(id, (map.get(id) ?? 0) + r._count._all);
  }
  return map;
}

export function serializeContractPayload(

  contract: ProviderContractRow | null,

  registeredCount: number,

  maxOverenrollmentPercent: number,

) {

  if (!contract) {

    return {

      configured: false,

      locked: false,

      contractTarget: null,

      maxOverenrollmentPercent,

      maxAllowedRegistration: null,

      registeredTrainees: registeredCount,

      effectiveFrom: null,

      notes: null,

    };

  }

  const maxAllowed = maxAllowedRegistration(contract.contractTarget, maxOverenrollmentPercent);

  return {

    configured: true,

    locked: true,

    contractTarget: contract.contractTarget,

    maxOverenrollmentPercent,

    maxAllowedRegistration: maxAllowed,

    registeredTrainees: registeredCount,

    effectiveFrom: contract.effectiveFrom?.toISOString().slice(0, 10) ?? null,

    notes: contract.notes,

  };

}


