const qs = require('qs');

exports.ListResponse = ({
    req,
    res,
    data = [],
    page = 1,
    limit = 10,
    total = 0,
    message = 'Data successfully retrieved',
}) => {
    const totalPages = Math.ceil(total / limit);
    const path = req.originalUrl?.split('?')[0] || req.path || '';
    const baseUrl = `${req.protocol}://${req.get('host')}${path}`;

    // Ambil query selain page
    const query = { ...req.query };
    delete query.page;

    const makeLink = (targetPage) => {
        if (targetPage < 1 || targetPage > totalPages) return null;
        const queryString = qs.stringify({ ...query, page: targetPage, limit });
        return `${baseUrl}?${queryString}`;
    };

    const pagination = {
        total,
        count: data.length,
        per_page: limit,
        current_page: page,
        total_pages: totalPages,
        offset: (page - 1) * limit,
        links: {
            next: makeLink(page + 1),
            previous: makeLink(page - 1)
        }
    };

    return res.status(200).json({
        success: true,
        message,
        data,
        pagination
    });
};