local kong_meta = require "kong.meta"
local cjson_safe = require "cjson.safe"

local ForceHttps = {PRIORITY = 1150, VERSION = kong_meta.version}

function ForceHttps:access(conf)
    if kong.request.get_scheme() ~= "https" and
        kong.request.get_header("X-Forwarded-Proto") ~= "https" then
        local resp = ""
        if conf.error_format == "dataapi" then
            resp = cjson_safe.encode({
                type = "",
                data = {
                    columns = {},
                    rows = {},
                    result = {
                        start_ms = 0,
                        end_ms = 0,
                        latency = "",
                        row_count = 0,
                        row_affect = 0,
                        limit = 0,
                        code = 30100001,
                        message = "HTTPS is required for this API endpoint"
                    }
                }
            })
        end
        kong.response.exit(conf.status_code, resp, {
            ["location"] = "https://" .. kong.request.get_host() ..
                kong.request.get_path_with_query()
        })
    end
end

return ForceHttps
