import { Router } from "@fastly/expressly";

const router = new Router();
const LOOKUP_LOOP_LIMIT = 16;

router.get("(.*)", async (req, res) => {
   
    let lookupresult = lookupRedirects(req.hostname, req.path);
    if (lookupresult!= null) {
        let json_result = JSON.parse(lookupresult);
        if ((json_result.keep_query == true)&&(req.query.toString() != "")){
          json_result.path = json_result.path + "?" + req.query;
        }
        res.redirect(json_result.path, json_result.status);
    }else{
     res.send(await fetch(
        req, { backend: "origin_0" }
    ));       
    }

});

router.listen();

function lookupRedirects(host, path) {
    const redirects = new ConfigStore('redirects');

    // (1) Look up with host + path
    let key = '';
    if (host && path) {
        key = host + path;
        const params = redirects.get(key);
        if (params) {
            return params;
        }
    }

    // (2) Look up with path.
    if (path) {
        key = path;
        const params = redirects.get(key);
        if (params) {
            return params;
        }
    }

    // (3) Look up with host + path + wildcard.
    if (host && path) {
        key = host + path.trimEnd('/');
        let wildcardLookupAttempt = 0;

        // Perform two rounds of wildcard lookups.
        // One for "(3) host + path + wildcard", another for "(4) path + wildcard".
        for (let i = 0; i < 2; i++) {
            // Wildcard lookup is done recursively until the lookup count limit is reached
            // or all directories have had a chance to match on a wildcard.
            while (key.includes('/') && wildcardLookupAttempt < LOOKUP_LOOP_LIMIT) {
                key += '/*';
                const params = redirects.get(key);
                if (params) {
                    return params;
                }
                // Remove "/*".
                key = key.slice(0, -2);
                // Remove the right most path segment.
                const n = key.lastIndexOf('/');
                if (n !== -1) {
                    key = key.slice(0, n);
                }
                wildcardLookupAttempt++;
            }
            // (4) Look up with path + wildcard.
            key ="";
            key = path.trimEnd('/');
        }
    }

    console.log('No redirection entry found');
    return null;
}