import { toIsoDateYmdFromDate } from "@/lib/frontend/search/dateRange";

function toLocalDay(date) {
	if (!(date instanceof Date) || Number.isNaN(date.getTime())) {
		return new Date();
	}

	return new Date(date.getFullYear(), date.getMonth(), date.getDate());
}

function addDays(date, deltaDays) {
	const d = toLocalDay(date);
	d.setDate(d.getDate() + Number(deltaDays || 0));
	return d;
}

function startOfMonth(date) {
	const d = toLocalDay(date);
	return new Date(d.getFullYear(), d.getMonth(), 1);
}

function startOfPrevMonth(date) {
	const d = toLocalDay(date);
	return new Date(d.getFullYear(), d.getMonth() - 1, 1);
}

function endOfPrevMonth(date) {
	const d = toLocalDay(date);
	// Day 0 of current month = last day of previous month.
	return new Date(d.getFullYear(), d.getMonth(), 0);
}

function startOfYear(date) {
	const d = toLocalDay(date);
	return new Date(d.getFullYear(), 0, 1);
}

export const DATE_PRESET_KEY = Object.freeze({
	TODAY: "today",
	YESTERDAY: "yesterday",
	LAST_7_DAYS: "last_7_days",
	LAST_30_DAYS: "last_30_days",
	THIS_MONTH: "this_month",
	LAST_MONTH: "last_month",
	THIS_YEAR: "this_year",
});

/**
 * Build German-labeled date presets for the Search date filter.
 *
 * All outputs are ISO YYYY-MM-DD strings (local calendar values, no timezone drift).
 *
 * @param {{ now?: Date }} args
 * @returns {Array<{ key: string, label: string, from: string, to: string }>}
 */
export function buildDatePresets({ now = new Date() } = {}) {
	const today = toLocalDay(now);

	const presets = [
		{
			key: DATE_PRESET_KEY.TODAY,
			label: "Heute",
			from: today,
			to: today,
		},
		{
			key: DATE_PRESET_KEY.YESTERDAY,
			label: "Gestern",
			from: addDays(today, -1),
			to: addDays(today, -1),
		},
		{
			key: DATE_PRESET_KEY.LAST_7_DAYS,
			label: "Letzte 7 Tage",
			from: addDays(today, -6),
			to: today,
		},
		{
			key: DATE_PRESET_KEY.LAST_30_DAYS,
			label: "Letzte 30 Tage",
			from: addDays(today, -29),
			to: today,
		},
		{
			key: DATE_PRESET_KEY.THIS_MONTH,
			label: "Dieser Monat",
			from: startOfMonth(today),
			to: today,
		},
		{
			key: DATE_PRESET_KEY.LAST_MONTH,
			label: "Letzter Monat",
			from: startOfPrevMonth(today),
			to: endOfPrevMonth(today),
		},
		{
			key: DATE_PRESET_KEY.THIS_YEAR,
			label: "Dieses Jahr",
			from: startOfYear(today),
			to: today,
		},
	];

	return presets.map((p) => ({
		key: p.key,
		label: p.label,
		from: toIsoDateYmdFromDate(p.from),
		to: toIsoDateYmdFromDate(p.to),
	}));
}
