vcl 4.1;

import std;

backend default {
    .host = "app";
    .port = "3000";
    .first_byte_timeout = 60s;
}

acl purge {
    "localhost";
    "127.0.0.1";
    "infra";
}

sub vcl_recv {
    if (req.method == "PURGE") {
        if (!client.ip ~ purge) {
            return (synth(405, "Not allowed."));
        }
        return (purge);
    }

    if (req.method != "GET" && req.method != "HEAD") {
        return (pass);
    }

    if (req.url ~ "^/gatekeeper" || req.url ~ "^/directus" || req.url ~ "^/admin") {
        return (pass);
    }

    if (req.url ~ "^/api/preview" || req.url ~ "^/health") {
        return (pass);
    }

    if (req.url ~ "\.(png|gif|jpg|jpeg|svg|ico|webp|js|css|woff|woff2|otf|ttf)$") {
        unset req.http.Cookie;
    }

    if (req.http.Cookie) {
        set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(__utm.|_ga.|_gid.|_gat)(=[^;]*)?", "");
        set req.http.Cookie = regsub(req.http.Cookie, "^;\s*", "");
        if (req.http.Cookie ~ "^\s*$") {
            unset req.http.Cookie;
        }
    }

    return (hash);
}

sub vcl_backend_response {
    if (bereq.url ~ "\.(png|gif|jpg|jpeg|svg|ico|webp|js|css|woff|woff2|otf|ttf)$") {
        set beresp.ttl = 1w;
    }

    if (beresp.http.Cache-Control ~ "private" ||
        beresp.http.Cache-Control ~ "no-cache" ||
        beresp.http.Cache-Control ~ "no-store") {
        set beresp.uncacheable = true;
        return (deliver);
    }

    if (beresp.ttl <= 0s) {
        set beresp.ttl = 120s;
    }

    return (deliver);
}

sub vcl_deliver {
    if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT";
        set resp.http.X-Cache-Hits = obj.hits;
    } else {
        set resp.http.X-Cache = "MISS";
    }
}
