local helpers = require "spec.helpers"

for _, strategy in helpers.each_strategy() do
    describe("Plugin: inner-basic-auth [#" .. strategy .. "]", function()
        local proxy_client
        local test_key_encode = "dGVzdDE6ZGV2OjE2ODAwNzY2MzcuNjg6NnRnNnB5Y0c="

        lazy_setup(function()
            local bp = helpers.get_db_utils(strategy,
                                            {"routes", "services", "plugins"})

            local service1 = bp.services:insert{
                protocol = "http",
                host = helpers.mock_upstream_host,
                port = helpers.mock_upstream_port
            }

            local route1 = bp.routes:insert{
                protocols = {"http", "https"},
                hosts = {"test1.com"},
                service = service1
            }
            bp.plugins:insert{
                route = {id = route1.id},
                name = "inner-basic-auth",
                config = {authkey_list = test_key_encode, env_type = "dev"}
            }

            assert(helpers.start_kong({
                database = strategy,
                nginx_conf = "spec/fixtures/custom_nginx.template",
                plugins = "inner-basic-auth"
            }))
        end)

        lazy_teardown(function()
            helpers.stop_kong()
        end)

        before_each(function()
            proxy_client = helpers.proxy_client()
        end)

        after_each(function()
            if proxy_client then
                proxy_client:close()
            end
        end)

        describe("Normal", function()
            it("/status/200 no auth header return 401", function()
                local res = assert(proxy_client:send({
                    method = "GET",
                    path = "/status/200",
                    headers = {["Host"] = "test1.com"}
                }))
                assert.res_status(401, res)
            end)
            it("/status/200 with auth header return 200", function()
                local res = assert(proxy_client:send({
                    method = "GET",
                    path = "/status/200",
                    headers = {
                        ["Host"] = "test1.com",
                        ["Authorization"] = "basic " .. test_key_encode
                    }
                }))
                assert.res_status(200, res)
            end)
        end)
    end)
end
