const SORT_DIRECTIONS = new Set(['ASC', 'DESC']);

function sanitizeSort(column, direction, allowedColumns = [], defaultColumn = 'id') {
    const safeColumn = allowedColumns.includes(column) ? column : defaultColumn;
    const normalizedDirection = String(direction || 'DESC').toUpperCase();
    const safeDirection = SORT_DIRECTIONS.has(normalizedDirection) ? normalizedDirection : 'DESC';
    return [safeColumn, safeDirection];
}

function toSafeInt(value, fallback = 0, min = 0, max = Number.MAX_SAFE_INTEGER) {
    const parsed = Number.parseInt(value, 10);
    if (!Number.isFinite(parsed)) {
        return fallback;
    }
    return Math.min(Math.max(parsed, min), max);
}

function sanitizePagination(offsetVal, limitVal, options = {}) {
    const {
        defaultOffset = 0,
        defaultLimit = 10,
        minOffset = 0,
        maxOffset = Number.MAX_SAFE_INTEGER,
        minLimit = 1,
        maxLimit = 100
    } = options;

    return {
        safeOffset: toSafeInt(offsetVal, defaultOffset, minOffset, maxOffset),
        safeLimit: toSafeInt(limitVal, defaultLimit, minLimit, maxLimit)
    };
}

module.exports = {
    sanitizeSort,
    sanitizePagination,
    toSafeInt
};
