import { RequestHandler } from 'express';
import { BadRequestError, ErrorCodes } from '../../business/errors';
import { OrderItem } from '../../business/interfaces/listInterface';
import { Sortable } from '../../business/interfaces/sortable';
import { getOrderItemByFieldAndOrder } from '../../infrastructure/helpers/sortable';
import { HumandResponse } from '../types/response';
import { SortableVC } from '../validationClasses/sortableVC';
import { genericValidateParams } from './genericValidateParams';

export const validateSortingParams = (sortableClass?: new () => Sortable): RequestHandler<any, HumandResponse, any, any> =>
    genericValidateParams(
        (req) => req.query,
        (res, output: SortableVC) => {
            const { orderBy, order } = output;
            if (!orderBy && !order) return;
            else if ((orderBy && !order) || (!orderBy && order) || orderBy?.length !== order?.length) {
                throw new BadRequestError('orderBy must be of the same length as order.', ErrorCodes.BAD_REQUEST);
            }
            const sortingOptions: OrderItem[] = [];
            const sortable = sortableClass ? new sortableClass() : undefined;
            if (orderBy && order) {
                orderBy.forEach((column, index) => {
                    const orderItem = getOrderItemByFieldAndOrder(column, order[index], sortable);
                    sortingOptions.push(orderItem);
                });
            }
            res.locals.sortingOptions = sortingOptions.length > 0 ? sortingOptions : undefined;
        },
        SortableVC,
    );
