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

public class TestingAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public const string SchemeName = "Testing";
    public const string DefaultTestUserId = "00000000-0000-0000-0000-000000000001";

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

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        if (!Request.Headers.TryGetValue("X-Test-Role", out var roleHeader))
            return Task.FromResult(AuthenticateResult.NoResult());

        var role = roleHeader.ToString();
        var userId = Request.Headers.TryGetValue("X-Test-User-Id", out var idHeader)
            ? idHeader.ToString()
            : DefaultTestUserId;

        var claims = new[]
        {
            new Claim(ClaimTypes.NameIdentifier, userId),
            new Claim(ClaimTypes.Name, $"test-{role.ToLowerInvariant()}"),
            new Claim("display_name", $"Test {role}"),
            new Claim("clinical_role", role.ToUpperInvariant()),
        };

        var identity = new ClaimsIdentity(claims, SchemeName);
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, SchemeName);
        return Task.FromResult(AuthenticateResult.Success(ticket));
    }
}
