local exporter = require "kong.plugins.prometheus.exporter"
local json = require "cjson.safe"

local UPSTREAM_LATENCY_BUCKETS = {
    25, 50, 80, 100, 250, 400, 700, 1000, 2000, 5000, 10000, 30000, 60000
}
local metrics = {}
local prometheus = exporter.get_prometheus()
metrics.custom_http_status = prometheus:counter("custom_http_status",
                                                "HTTP status codes in Kong", {
    "kube_service", "code", "host", "path", "request_type"
})
metrics.total_latency = prometheus:histogram("custom_request_latency_ms",
                                             "Total latency incurred during requests",
                                             {
    "kube_service", "host", "path", "request_type"
}, UPSTREAM_LATENCY_BUCKETS)

local Prom = {}
Prom.PRIORITY = -1

local labels_table = {0, 0, 0, 0, 0}
local latency_labels_table = {0, 0, 0, 0}

function Prom:log(conf)
    if not metrics then
        kong.log.err(
            "prometheus: can not log metrics because of an initialization " ..
                "error, please make sure that you've declared " ..
                "'prometheus_metrics' shared dict in your nginx template")
        return
    end

    local message = kong.log.serialize()
    local service_name
    if message and message.service then
        service_name = message.service.name or message.service.host
    else
        -- do not record any stats if the service is not present
        return
    end

    local path
    if message and message.route then
        if message.route.paths and message.route.paths[1] then
            path = message.route.paths[1]
        else
            path = message.route.name or message.route.id
        end
    end
    if not path then
        return
    end

    local request_type = "normal"
    if kong.request.get_header("X-FUNCTION-TEST") == "true" then
        request_type = "qa-test"
    end
    labels_table[1] = service_name
    labels_table[2] = message.response.status
    labels_table[3] = ngx.var.host
    labels_table[4] = path
    labels_table[5] = request_type
    metrics.custom_http_status:inc(1, labels_table)

    latency_labels_table[1] = service_name
    latency_labels_table[2] = ngx.var.host
    latency_labels_table[3] = path
    latency_labels_table[4] = request_type

    local request_latency = message.latencies.request
    if request_latency and request_latency >= 0 then
        metrics.total_latency:observe(request_latency, latency_labels_table)
    end

end

return Prom
