import { NextApiRequest, NextApiResponse } from 'next';

/**
 * On-demand revalidation handler
 * https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration
 * @param req Request
 * @param res Response
 * @returns Result
 */
export function OnDemandHandler(token: string, scheme = 'NextJsToken') {
    return async function (req: NextApiRequest, res: NextApiResponse) {
        // Check for secret to confirm this is a valid request
        const auth = req.headers['authorization'];
        if (auth !== `${scheme} ${token}`) {
            return res.status(401).json({
                message: `Invalid token with ${scheme}, expected ${token.hideData()} but with ${auth?.hideData()}`
            });
        }

        // Check url
        const url = req.query.url;
        if (url == null || url === '') {
            return res.status(400).json({ message: 'Invalid URL' });
        }

        try {
            console.log(`Static page generation on demand for URL(s): ${url}`);

            // this should be the actual path not a rewritten path
            // e.g. for "/blog/[slug]" this should be "/blog/post-1"
            const urls = typeof url === 'string' ? [url] : url;

            // Always revalidate home page
            if (!urls.includes('/')) {
                urls.push('/');
            }

            // Validate each URL
            await Promise.all(
                urls.map((item) => res.revalidate(decodeURI(item)))
            );

            return res.json({ ok: true });
        } catch (err) {
            // If there was an error, Next.js will continue
            // to show the last successfully generated page
            console.log(err);
            return res.status(500).send('Exception when revalidating');
        }
    };
}
