package dev.dinauer.maven;

import io.quarkus.oidc.client.NamedOidcClient;
import io.quarkus.oidc.client.OidcClient;
import io.quarkus.oidc.client.Tokens;
import jakarta.annotation.security.PermitAll;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.NewCookie;
import jakarta.ws.rs.core.Response;

import java.net.URI;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Map;

@Path("/callback")
public class OidcCallback
{
    @Inject
    @NamedOidcClient("ac")
    OidcClient client;

    @GET
    public Response callback(@QueryParam("code") String code)
    {
        Tokens tokens = client.getTokens(grantParams(code)).await().indefinitely();
        NewCookie cookie = new NewCookie.Builder("session").value(tokens.getAccessToken()).path("/").maxAge((int) (tokens.getAccessTokenExpiresAt() - ZonedDateTime.now().toEpochSecond())).secure(false).httpOnly(true).build();
        return Response.seeOther(URI.create("http://localhost:3000")).cookie(cookie).build();
    }

    private Map<String, String> grantParams(String code)
    {
        return Map.ofEntries(
            Map.entry("grant_type", "authorization_code"),
            Map.entry("code", code),
            Map.entry("redirect_uri", "redirectUri")
        );
    }
}
