import ValidationError from '@/shared/errors/validation';
import { ISO_DATE_PATTERN } from '@/shared/constants/validation';

/** Parses a positive-integer list limit, defaulting and capping it. */
export function clampLimit(
  value: unknown,
  defaultLimit: number,
  maxLimit: number,
): number {
  if (value === undefined) {
    return defaultLimit;
  }

  const limit = Number(value);

  if (!Number.isInteger(limit) || limit <= 0) {
    throw new ValidationError();
  }

  return Math.min(limit, maxLimit);
}

/** Trims a string, returning null for non-strings or blanks. */
export function nullableString(value: unknown): string | null {
  if (typeof value !== 'string' || value.trim().length === 0) {
    return null;
  }
  return value.trim();
}

/** Requires an ISO calendar date (`YYYY-MM-DD`); throws otherwise. */
export function requiredIsoDate(value: unknown): string {
  if (typeof value !== 'string' || !ISO_DATE_PATTERN.test(value)) {
    throw new ValidationError();
  }
  return value;
}

/** Like {@link requiredIsoDate}, but `undefined` yields `null` (optional). */
export function optionalIsoDate(value: unknown): string | null {
  if (value === undefined) {
    return null;
  }
  return requiredIsoDate(value);
}
