local cjson = require "cjson"
local http_cache = require("http_cache")

ngx.header["Server"] = "AGC-CDN"
local cache_status = (ngx.var.upstream_cache_status or "")
ngx.header["AGC-Cache-Status"] = cache_status
if cache_status == "MISS" or cache_status == "EXPIRED" then
    ngx.log(ngx.INFO, "cache_config: " .. ngx.var.cache_config)
    ngx.log(ngx.INFO, "cache_config is not empty: " .. cjson.encode((not (ngx.var.cache_config == ""))))
    if not (ngx.var.cache_config == "") then
        local cache_data = http_cache.get_metadata()
        local cache_config = cjson.decode(ngx.var.cache_config)
        local new_expire = ngx.time() + cache_config.expiration_time
        ngx.log(ngx.INFO, "new_expire: " .. new_expire)

        local response_status = ngx.status or 0
        ngx.log(ngx.INFO, "response_status: " .. tostring(response_status))
        if response_status ~= 200 then
            ngx.log(ngx.INFO, "skip setting cache metadata due to non-OK status: " .. tostring(response_status))
        else
            if cache_data and cache_data["valid_sec"] then
                http_cache.set_metadata({
                    valid_sec = new_expire,
                    fcn = {
                        valid_sec = new_expire,
                        expire = new_expire
                    }
                })
            end
        end
    end
end
ngx.log(ngx.INFO, "cache_data: " .. cjson.encode(http_cache.get_metadata()))

local origin_response_headers = ngx.var.origin_response_headers
if ngx.ctx.origin_response_headers then
    for _, header in ipairs(ngx.ctx.origin_response_headers or {}) do
        ngx.header[header.name] = header.value
    end
end
