import { ApiClientError } from "@/lib/frontend/apiClient";
import { getSearchDateRangeValidation } from "@/lib/frontend/search/searchDateValidation";

function isNonEmptyString(value) {
	return typeof value === "string" && value.trim().length > 0;
}

function toTrimmedOrNull(value) {
	return isNonEmptyString(value) ? value.trim() : null;
}

/**
 * Build a local validation error for date filters.
 *
 * This is intentionally independent from the search query "q" so the UI can
 * validate immediately while the user edits the date range.
 *
 * Single Source of Truth:
 * - Uses getSearchDateRangeValidation(...) as the canonical validator.
 *
 * @param {{ from?: string|null, to?: string|null }} input
 * @returns {ApiClientError|null}
 */
export function buildDateFilterValidationError({
	from = null,
	to = null,
} = {}) {
	const f = toTrimmedOrNull(from);
	const t = toTrimmedOrNull(to);

	const v = getSearchDateRangeValidation(f, t);
	if (!v) return null;

	return new ApiClientError({
		status: 400,
		code: v.code,
		message: v.message,
		details: v.details,
	});
}
