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

namespace WorkTracker.Services.Auth;

public sealed class DefaultAdminAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public const string SchemeName = "DefaultAdmin";

    private readonly IOptions<AppAuthOptions> appAuthOptions;

    public DefaultAdminAuthenticationHandler(
        IOptionsMonitor<AuthenticationSchemeOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder,
        IOptions<AppAuthOptions> appAuthOptions)
        : base(options, logger, encoder)
    {
        this.appAuthOptions = appAuthOptions;
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var configuredOptions = appAuthOptions.Value;
        var username = string.IsNullOrWhiteSpace(configuredOptions.DefaultUsername)
            ? "Admin"
            : configuredOptions.DefaultUsername.Trim();
        var userId = string.IsNullOrWhiteSpace(configuredOptions.DefaultUserId)
            ? username.ToUpperInvariant()
            : configuredOptions.DefaultUserId.Trim();

        var claims = new List<Claim>
        {
            new(ClaimTypes.NameIdentifier, userId),
            new(ClaimTypes.Name, username),
            new(ClaimTypes.Role, "Admin")
        };

        var identity = new ClaimsIdentity(claims, SchemeName);
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, SchemeName);

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