import type { InferResultType } from "@/utils/drizzle";

export interface AbortReasonCount {
	abortReason: string;
	count: number;
}

/**
 * Calculates the count of each unique abort reason for print jobs.
 *
 * @param pJobs - Array of print job objects.
 * @returns An array of AbortReasonCount objects, each containing the abort reason and its count.
 */
export function calculateAbortReasonsCount(pJobs: InferResultType<"printJobs">[]): AbortReasonCount[] {
	if (pJobs.length === 0) {
		return []; // No jobs, no data.
	}

	// Filter aborted jobs and count each abort reason
	const abortReasonsCount = pJobs
		.filter((job) => job.aborted && job.abortReason) // Consider only aborted jobs with a reason
		.reduce(
			(acc, job) => {
				const reason = job.abortReason || "Unbekannter Grund";
				if (!acc[reason]) {
					acc[reason] = 0;
				}
				acc[reason]++;
				return acc;
			},
			{} as Record<string, number>,
		);

	// Convert the result to an array of AbortReasonCount objects
	return Object.entries(abortReasonsCount).map(([abortReason, count]) => ({
		abortReason,
		count,
	}));
}
