import type { printJobs } from "@/server/db/schema";
import { endOfDay, endOfMonth, endOfWeek, startOfDay, startOfMonth, startOfWeek } from "date-fns";
import type { InferSelectModel } from "drizzle-orm";

interface PrintVolumes {
	today: number;
	thisWeek: number;
	thisMonth: number;
}

/**
 * Calculates the number of print jobs for today, this week, and this month.
 *
 * @param printJobs - Array of print job objects.
 * @returns An object with counts of print jobs for today, this week, and this month.
 */
export function calculatePrintVolumes(pJobs: InferSelectModel<typeof printJobs>[]): PrintVolumes {
	const now = new Date();

	// Define time ranges with week starting on Monday
	const timeRanges = {
		today: { start: startOfDay(now), end: endOfDay(now) },
		thisWeek: {
			start: startOfWeek(now, { weekStartsOn: 1 }),
			end: endOfWeek(now, { weekStartsOn: 1 }),
		},
		thisMonth: { start: startOfMonth(now), end: endOfMonth(now) },
	};

	// Initialize counts
	const volumes: PrintVolumes = {
		today: 0,
		thisWeek: 0,
		thisMonth: 0,
	};

	// Iterate over print jobs and count based on time ranges
	for (const job of pJobs) {
		const jobStart = new Date(job.startAt);
		if (jobStart >= timeRanges.today.start && jobStart <= timeRanges.today.end) {
			volumes.today += 1;
		}
		if (jobStart >= timeRanges.thisWeek.start && jobStart <= timeRanges.thisWeek.end) {
			volumes.thisWeek += 1;
		}
		if (jobStart >= timeRanges.thisMonth.start && jobStart <= timeRanges.thisMonth.end) {
			volumes.thisMonth += 1;
		}
	}

	return volumes;
}
