using Microsoft.AspNetCore.Http;
using {{ namespace }}.Auth;

namespace {{ namespace }}.Http;

/// <summary>Parses the `Authorization` header off an incoming HTTP request, if present.</summary>
public static class AuthExtractor
{
    public static string? ExtractAuthorizationHeader(IHeaderDictionary headers) =>
        headers.TryGetValue("Authorization", out var value) ? value.ToString() : null;

    /// <summary>
    /// Extracts the credential value for the active auth method's
    /// declared location (<see cref="AuthManager.HeaderLocationFor"/>)
    /// off an incoming HTTP request. The extracted value is relayed
    /// verbatim to the facaded API — whatever the caller sent, prefixed
    /// or not. Returns null if the location isn't a relayable header, or
    /// the header is missing/empty — used both by the auth-gate (401 on
    /// null, for non-localhost callers) and
    /// <see cref="HttpRequestCredentialProvider"/> (null there is a
    /// signal to <see cref="AuthManager.ApplyAuthHeadersAsync"/> that no
    /// per-request credentials are available).
    /// </summary>
    public static RequestCredentials? ExtractRequestCredentials(
        IHeaderDictionary headers, string headerLocation, string headerName)
    {
        if (headerLocation != "header")
        {
            return null;
        }

        if (!headers.TryGetValue(headerName, out var value) || string.IsNullOrEmpty(value))
        {
            return null;
        }

        return new RequestCredentials(headerName, value.ToString());
    }
}
