using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;

namespace Fast.Shared.Logic;

public class SharedSecretAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    private const string SharedSecretKey = FastValues.SharedSecret;

    public SharedSecretAuthenticationHandler(
        IOptionsMonitor<AuthenticationSchemeOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder)
        : base(options, logger, encoder)
    {
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        if (!Context.Request.Headers.TryGetValue("X-Shared-Secret", out var requestSecret) ||
            requestSecret != SharedSecretKey)
        {
            return Task.FromResult(AuthenticateResult.Fail("Invalid shared secret."));
        }

        var claims = new[] { new Claim(ClaimTypes.Name, "SharedSecretUser") };
        var identity = new ClaimsIdentity(claims, Scheme.Name);
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, Scheme.Name);

        return Task.FromResult(AuthenticateResult.Success(ticket));
    }
}
