local kong_meta = require "kong.meta"

-- Gradual rollout compatibility: Bearer Token fallback plugin
-- Used for smooth migration to Cookie Auth, can be removed after rollout completes
local BearerTokenFallback = { PRIORITY = 1270, VERSION = kong_meta.version }

local function with_bearer_token(conf)
    local auth_header = kong.request.get_header("authorization")
    if not auth_header then
        return false
    end

    local match = ngx.re.match(auth_header, "^[Bb]earer\\s.", "oj")

    return match
end

local function with_query_jwt(conf)
    local jwt = kong.request.get_query_arg("jwt")
    if jwt and jwt ~= "" then
        return true
    end
    return false
end


function BearerTokenFallback:access(conf)
    if with_bearer_token(conf) then
        -- Has Bearer token, mark as authenticated to skip cookie-auth
        kong.ctx.shared.has_authed = true
        kong.log.info("bearer token fallback: skip cookie auth, trace_id: ",
            kong.ctx.shared.trace_id or "-")
        return
    end

    if with_query_jwt(conf) then
        -- Has JWT query param, mark as authenticated to skip cookie-auth
        kong.ctx.shared.has_authed = true
        kong.log.info("query jwt fallback: skip cookie auth, trace_id: ",
            kong.ctx.shared.trace_id or "-")
        return
    end
end

return BearerTokenFallback
