using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using {{ namespace }}.Auth;
using {{ namespace }}.Core;

namespace {{ namespace }}.Http;

/// <summary>
/// Resolves this call's HTTP-transport request credentials, if any — the
/// one seam between ASP.NET Core's per-request DI scope (which
/// <c>MapMcp</c>'s tool invocation is resolved from, same as any other
/// ASP.NET Core request) and the auth pipeline. Registered scoped, backed
/// by <see cref="IHttpContextAccessor"/>: outside an HTTP request (stdio,
/// or the bundled CLI's direct in-process tool calls — see
/// <c>Cli/Roles.cs</c>) <see cref="IHttpContextAccessor.HttpContext"/> is
/// null, so <see cref="GetOverride"/> naturally returns null there too —
/// no separate stdio/CLI code path needed.
/// </summary>
public interface IRequestCredentialProvider
{
    RequestCredentials? GetOverride();
}

public sealed class HttpRequestCredentialProvider(
    IHttpContextAccessor httpContextAccessor, IOptions<McpifyOptions> options) : IRequestCredentialProvider
{
    public RequestCredentials? GetOverride()
    {
        var headers = httpContextAccessor.HttpContext?.Request.Headers;
        if (headers is null)
        {
            return null;
        }

        var (headerLocation, headerName) = AuthManager.HeaderLocationFor(options.Value.AuthMethod);
        return AuthExtractor.ExtractRequestCredentials(headers, headerLocation, headerName);
    }
}
