---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by hartnett.
--- DateTime: 2019/11/10 21:40
---

local ngx = ngx
local string = string
local http = require("resty.http")
local core = require("apisix.core")
local redis = require("apisix.core.redis")

local fetch_local_conf = require("apisix.core.config_local").local_conf
local config = fetch_local_conf()

local notice_api = config.api.notice_api
local active_url = config.api.ews_active
local CLIENT_TYPEs = {}

-- send notice
local function send_notice(username, phone, content, user_agent, client_type, remote_ip, code)
    core.log.warn(string.format("username: %s, content: %s", username, content))

    local data = string.format("content=%s&username=%s", content, username)
    local headers = { ["Content-Type"] = "application/x-www-form-urlencoded", ["Content-Length"] = #data }

    local http_client = http.new()
    local res, err = http_client:request_uri(notice_api, {
        method = "POST",
        body = data,
        headers = headers,
    })

    if res ~= nil and res.status == 200 then
        core.log.warn(string.format("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s",
                "ews_send_sms", ngx.localtime(), username, remote_ip, client_type, user_agent, phone, code, true))
    end
end

local function check_auth(username, remote_ip)
    opa_url = string.format("%s%s", config.api.opa_host, config.api.opa_port)

end

-- 生成邮件内容
local function generate_ews_content(username, client_type, remote_ip, iplist, code)
    local client_type_alias = CLIENT_TYPEs[client_type] or client_type
    local content = string.format("您的邮箱: %s 正在使用 %s 客户端，从来源IP: %s 同步邮件，请点击链接查看详情并允许或拒绝。%s%s （此链接30分钟后失效）",
            username, client_type_alias, remote_ip, active_url, code)
    return content
end


-- 判断是否需要调用短信接口通知用户激活设备
-- 24小时内只发送5次激活码，每次发送激活码的时间间隔为10小时，降低晚上对用户的打拢

local function send_ews_active_code(username, user_agent, client_type, remote_ip, iplist, code, phone)
    local status = true

    local times = 1
    local ua = ""
    local send_time = ngx.now()

    local key = string.format("EWS_SMS_%s", username)
    local redis_cli = redis.new()
    local res, err = redis_cli:hmget(key, "times", "send_time", "user_agent")

    if err == nil and res ~= nil and type(res[1]) == "string" then
        times = tonumber(res[1])
        send_time = res[2]
        ua = res[3]
        local now = ngx.now()

        -- 不再控制激活的次数，只限制发送频率，每12小时只推送一次
        if now - send_time > 60 * 60 * 12 then
            times = times + 1
            send_time = now
            redis_cli:hmset(key, "times", times, "send_time", send_time, "src_ip", remote_ip)
            local content = generate_ews_content(username, client_type, remote_ip, iplist, code)
            send_notice(username, phone, content, user_agent, client_type, remote_ip, code)
        else
            -- 通知频率太快，直接退出
            status = false
            ngx.exit(ngx.HTTP_OK)
        end
    else
        redis_cli:hmset(key, "times", times, "send_time", send_time, "src_ip", remote_ip,
                "last_code", code, "user_agent", user_agent)

        local content = generate_ews_content(username, client_type, remote_ip, iplist, code)
        send_notice(username, phone, content, user_agent, client_type, remote_ip, code)
    end
    return status
end

-- 重置通知的激活码状态，方便在激活码使用之后还可以再次激活（忽略之后可以再次发送，要不然忽略之后就没法激活了）
local function reset_status(username, remote_ip)
    local key = string.format("EWS_SMS_%s", username)
    local redis_cli = redis.new()
    redis_cli:del(key)
end

local _M = {
    send_ews_active_code = send_ews_active_code,
    reset_status = reset_status,
}

return _M