
function getPageLink(req, pageIndex) {
    if (pageIndex == null) {
        return;
    }

    let urlParts = (req.originalUrl || req.url || '').split('?');

    if (urlParts[0]) {
        urlParts[0] = urlParts[0].replace(/\/page\/\d+/, '');
        urlParts[0] += pageIndex === 1 ? (urlParts[0] ? '' : '/') : '/page/' + pageIndex;
    }

    if (urlParts[1])
        urlParts[1] = '?' + urlParts[1];

    return urlParts.join('').replace(/\/+/, '/');
}

function preprocessPagedList(req, data) {
    if (!data) return {};

    let links = {};

    if (data.page > 1 || (data.links && data.links.prev)) {
        links.prev = getPageLink(req, data.page - 1);
        links.first = getPageLink(req, 1);
    }

    if (data.page < data.pages || (data.links && data.links.next)) {
        links.next = getPageLink(req, data.page + 1);
        links.last = getPageLink(req, data.pages);
    }

    if (Object.keys(links).length)
        data.links = links;

    return data;
}

module.exports = preprocessPagedList;
