package dev.dinauer.maven;

import io.quarkus.oidc.AccessTokenCredential;
import io.quarkus.security.credential.PasswordCredential;
import io.quarkus.security.credential.TokenCredential;
import io.quarkus.security.identity.IdentityProviderManager;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.security.identity.request.TokenAuthenticationRequest;
import io.quarkus.security.identity.request.UsernamePasswordAuthenticationRequest;
import io.quarkus.security.runtime.QuarkusSecurityIdentity;
import io.quarkus.vertx.http.runtime.security.ChallengeData;
import io.quarkus.vertx.http.runtime.security.HttpAuthenticationMechanism;
import io.quarkus.vertx.http.runtime.security.HttpSecurityUtils;
import io.smallrye.mutiny.Uni;
import io.vertx.core.http.Cookie;
import io.vertx.ext.web.RoutingContext;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import net.bytebuddy.implementation.bind.MethodDelegationBinder;
import org.jboss.logging.Logger;

@ApplicationScoped
public class CustomAuthenticationMechanism implements HttpAuthenticationMechanism
{
    private static final String SESSION_COOKIE = "session";

    @Override
    public Uni<SecurityIdentity> authenticate(RoutingContext context, IdentityProviderManager identityProviderManager)
    {
        context.put(CustomAuthenticationMechanism.class.getName(), this);
        Cookie cookie = context.request().getCookie(SESSION_COOKIE);
        if (cookie != null)
        {
            String value = cookie.getValue();
            TokenAuthenticationRequest request = new TokenAuthenticationRequest(new AccessTokenCredential(value));
            HttpSecurityUtils.setRoutingContextAttribute(request, context);
            return identityProviderManager.authenticate(request);
        }
        String authHeader = context.request().getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Basic "))
        {
            String[] sections = authHeader.split("\\s+");
            if (sections.length == 2)
            {
                UsernamePasswordAuthenticationRequest request = new UsernamePasswordAuthenticationRequest(sections[0], new PasswordCredential(sections[1].toCharArray()));
                HttpSecurityUtils.setRoutingContextAttribute(request, context);
                return identityProviderManager.authenticate(request);
            }
        }
        return Uni.createFrom().nullItem();
    }

    @Override
    public Uni<ChallengeData> getChallenge(RoutingContext context)
    {
        return Uni.createFrom().nullItem();
    }
}
