local http = require "resty.http"
local json = require "cjson"
local cookie = require 'resty.cookie'
local pbi =   require "ws_message_pb"

local i360_socket = "unix:/var/run/defence360agent/protobuf.sock"
local captchapassed = ngx.shared.captchapassed_clients

local function write_format(little_endian, format, ...)
  local res = ''
  local values = {...}
  for i=1,#format do
    local size = tonumber(format:sub(i,i))
    local value = values[i]
    local str = ""
    for j=1,size do
      str = str .. string.char(value % 256)
      value = math.floor(value / 256)
    end
    if not little_endian then
      str = string.reverse(str)
    end
    res = res .. str
  end
  return res
end


local function make_captcha_cookie_expire()
    local cookie_obj, err = cookie:new()
    if not cookie_obj then
        ngx.log(ngx.ERR, "Failed to init cookie: ", err)
        return
    end

    local current_timestamp = os.time()
    local expiration_date = os.date(
        "!%a, %d-%b-%y %H:%M:%S GMT", current_timestamp - 86400)  -- Let it expire

    local ok, err = cookie_obj:set({
        key = "cl-bypass-cache",
        value = "no",
        domain = ngx.var.host,
        samesite = "Lax",
        httponly = true,
        path = "/",
        expires = expiration_date
    })
    if not ok then
        ngx.log(ngx.ERR, "Could not set cookie: ", err)
    end
end


local function composeMessage(uid, ip, success)
    local msg = pbi.SendInfo()
    msg.ip = ip
    msg.method = msg.WEBSHIELD
    msg.timestamp = os.time(os.date("!*t"))

    if uid then   -- yes, UID might be absent
        msg.websh.user_id = uid
    end

    if success then
        msg.websh.captcha = msg.websh.PASSED
    else
        msg.websh.captcha = msg.websh.FAILED
    end

    local serialized = msg:SerializeToString()
    return write_format(false, "2", string.len(serialized)) .. serialized
end


local function get_value(key_name)
    ngx.req.read_body()
    local value
    local args = ngx.req.get_post_args()
    if args then
        for key, val in pairs(args) do
            if key == key_name then
                value = val
                break
            end
        end
    end
    return value
end


local function notify_peer (uid, ip, success)

    local sock = ngx.socket.tcp()
    sock:settimeout(1000)
    local ok, err = sock:connect(i360_socket)

    if not ok then
        ngx.log(ngx.ERR, "Could not connect to i360 socket: ", err)
        return
    end

    local sent, err = sock:send(composeMessage(uid, ip, success))

    if not sent then
        ngx.log(ngx.ERR, "Could not send to i360 socket: ", err)
    end

    ok, err, forced = captchapassed:set(ip, true, 240)
    if not ok then
        ngx.log(ngx.ERR, "Could not whitelist ", ip, " as captcha passed: ", err)
    end

    sock:close()
end


local function google_query (data, remote_address)

    local conn = http.new()
    local google_url = "https://www.google.com/recaptcha/api/siteverify"
    local default_secret_key = "6LfwghwUAAAAALdx_xobqogq6hpa4pR8usRovQl8"
    local custom_secret_key = ngx.var.wscaptcha_secret_key
    local captcha_secret_key = custom_secret_key or default_secret_key
    local body = string.format(
        "secret=%s&response=%s&remoteip=%s",
        captcha_secret_key, data, remote_address)

    local res, err = conn:request_uri(google_url, {
        method = "POST",
        body = body,
        headers = {
          ["Content-Type"] = "application/x-www-form-urlencoded",
        }
    })

    if not res then
        ngx.log(ngx.ERR, "Could not query google: ", err)
        return
    end

    local decoded = json.decode(res.body)

    if not decoded.success then
        ngx.log(ngx.ERR, "Captcha site verification error: [", table.concat(decoded["error-codes"], ", "), "]")
    end

    return decoded.success
end


local function send_OK ()
    ngx.status = ngx.HTTP_OK
    ngx.header.content_type = "application/json; charset=utf-8"
    ngx.say(json.encode({ success = true }))
    return ngx.exit(ngx.HTTP_OK)
end


local function send_ERR ()
    ngx.status = ngx.HTTP_BAD_REQUEST
    return ngx.exit(ngx.HTTP_BAD_REQUEST)
end


local function process ()

    local value = get_value("captcha_value")        -- get POST-passed value

    if not value then
        return send_ERR()
    end

    local userid   = ngx.var.wsuserid
    local remote_address = ngx.var.wsuserip

    local response = google_query(value, remote_address)

    if response == nil then
        return send_ERR()
    end

    notify_peer(userid, remote_address, response)

    make_captcha_cookie_expire()

    if response then
        return send_OK()
    end

    return send_ERR()
end


return process()