import { RequestHandler } from 'express';
import { BadRequestError } from '../../business/errors/badRequestError';
import { ErrorCodes } from '../../business/errors/errorCodes';
import { HumandResponse } from '../types/response';
import { TimestampPaginationVC } from '../validationClasses/timestampPaginationVC';
import { genericValidateParams } from './genericValidateParams';

export const MAX_LIMIT = 500;

export const validateTimestampPagination: RequestHandler<any, HumandResponse, any, any, any> = genericValidateParams(
    (req) => req.query,
    (res, output: TimestampPaginationVC) => {
        res.locals.timestampPagination = { limit: undefined };
        const { limit } = output;
        if (limit != null) {
            const newLimit = Number(output.limit);
            if (newLimit <= 0 || newLimit > MAX_LIMIT) {
                throw new BadRequestError(`The limit must be an integer between 1 and ${MAX_LIMIT}`, ErrorCodes.INVALID_DATA);
            }
            res.locals.timestampPagination.limit = newLimit;
        }
        if (output.timestamp) res.locals.timestampPagination.timestamp = new Date(output.timestamp);
    },
    TimestampPaginationVC,
);
