local core = require("apisix.core")
local cjson = require("cjson")
local ngx = ngx

local plugin_name = "unified-params"

local plugin_schema = {
    type = "object",
    properties = {}
}

local _M = {
    version = 1.0,
    priority = 1000,
    name = plugin_name,
    schema = plugin_schema
}
local function merge_object(first_table, second_table)
    local body = {}
    for key, value in pairs(first_table) do
        body[key] = value
    end
    for key, value in pairs(second_table) do
        body[key] = value
    end
    return body
end
function _M.init(conf, ctx)
    core.log.info("UNIFIED_PARAMS")
end

function _M.check_schema(conf)
    local ok, err = core.schema.check(plugin_schema, conf)
    if not ok then
        return false, err
    end

    return true
end

function _M.access(conf, ctx)
    ngx.req.read_body()
    local req_body_data = ngx.req.get_body_data()
    if not req_body_data or req_body_data == "" then
        core.log.warn("Request body is empty or nil")
        req_body_data = "{}"
    end
    local req_body_table, err = cjson.decode(req_body_data);
    local merged_path_variables = merge_object(req_body_table, ctx.curr_req_matched)
    local merged_all = merge_object(ngx.req.get_uri_args(), merged_path_variables)
    ngx.req.set_body_data(core.json.encode(merged_all))
    ngx.req.set_uri_args(merged_all)
end


return _M
