local ngx = ngx
local cjson = require "cjson"
local cache_manager = require "sm.service.cache_manager"

local _M = {}

-- 处理缓存统计API
function _M.handle_stats()
    local stats = cache_manager.get_stats()
    ngx.header.content_type = "application/json"
    ngx.say(cjson.encode(stats))
end

-- 处理缓存预热API
-- @param table urls 要预热的URL列表
function _M.handle_warmup(urls)
    if not urls or type(urls) ~= "table" then
        ngx.status = 400
        ngx.say(cjson.encode({
            error = "Invalid request body"
        }))
        return
    end

    local results = {
        success = {},
        failed = {}
    }

    for _, url in ipairs(urls) do
        local cache_key = ngx.md5(url)
        local ok, err = cache_manager.save_response(cache_key, url, 3600) -- 默认1小时TTL
        if ok then
            table.insert(results.success, url)
        else
            table.insert(results.failed, {
                url = url,
                error = err
            })
        end
    end

    ngx.header.content_type = "application/json"
    ngx.say(cjson.encode(results))
end

-- 处理缓存清理API
-- @param table urls 要清理的URL列表
function _M.handle_purge(urls)
    if not urls or type(urls) ~= "table" then
        ngx.status = 400
        ngx.say(cjson.encode({
            error = "Invalid request body"
        }))
        return
    end

    local results = {
        success = {},
        failed = {}
    }

    for _, url in ipairs(urls) do
        local cache_key = ngx.md5(url)
        local ok, err = cache_manager.delete_cache(cache_key)
        if ok then
            table.insert(results.success, url)
        else
            table.insert(results.failed, {
                url = url,
                error = err
            })
        end
    end

    ngx.header.content_type = "application/json"
    ngx.say(cjson.encode(results))
end

-- 处理缓存清理任务
function _M.handle_cleanup()
    cache_manager.cleanup_expired_cache()
    ngx.header.content_type = "application/json"
    ngx.say(cjson.encode({
        success = true,
        message = "Cache cleanup task started"
    }))
end

-- 处理API请求
function _M.handle_request()
    local method = ngx.req.get_method()
    local uri = ngx.var.uri

    -- 获取缓存统计信息
    if method == "GET" and uri == "/api/cache/stats" then
        _M.handle_stats()
        return
    end

    -- 处理POST请求
    if method == "POST" then
        ngx.req.read_body()
        local body = ngx.req.get_body_data()
        if not body then
            ngx.status = 400
            ngx.say(cjson.encode({
                error = "Missing request body"
            }))
            return
        end

        local data = cjson.decode(body)
        if not data then
            ngx.status = 400
            ngx.say(cjson.encode({
                error = "Invalid JSON in request body"
            }))
            return
        end

        -- 批量预热缓存
        if uri == "/api/cache/warmup" then
            _M.handle_warmup(data.urls)
            return
        end

        -- 批量清理缓存
        if uri == "/api/cache/purge" then
            _M.handle_purge(data.urls)
            return
        end

        -- 手动触发缓存清理
        if uri == "/api/cache/cleanup" then
            _M.handle_cleanup()
            return
        end
    end

    -- 未知的API端点
    ngx.status = 404
    ngx.say(cjson.encode({
        error = "API endpoint not found"
    }))
end

return _M 