package com.gbcm.client.resources;

import io.quarkus.qute.Template;
import io.quarkus.qute.TemplateInstance;
import io.quarkus.security.identity.SecurityIdentity;
import io.quarkus.oidc.OidcSession;
import io.quarkus.oidc.IdToken;
import org.eclipse.microprofile.jwt.JsonWebToken;

import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;

@Path("/")
public class HomeController {

    @Inject
    Template index;

    @Inject
    SecurityIdentity securityIdentity;

    @Inject
    OidcSession oidcSession;

    @Inject
    @IdToken
    JsonWebToken idToken;

    @GET
    @Produces(MediaType.TEXT_HTML)
    public TemplateInstance index() {
        return index
                .data("user", getCurrentUser())
                .data("authenticated", isAuthenticated())
                .data("title", "Accueil - GBCM");
    }

    @GET
    @Path("/index")
    @Produces(MediaType.TEXT_HTML)
    public TemplateInstance indexPage() {
        return index();
    }

    private boolean isAuthenticated() {
        return securityIdentity != null && !securityIdentity.isAnonymous();
    }

    private UserInfo getCurrentUser() {
        if (!isAuthenticated()) {
            return new UserInfo("Invité", "guest@example.com", "GUEST");
        }

        String username = securityIdentity.getPrincipal().getName();
        String email = idToken != null ? idToken.getClaim("email") : username;
        String role = securityIdentity.getRoles().isEmpty() ? "USER" : 
                     securityIdentity.getRoles().iterator().next();

        return new UserInfo(username, email, role);
    }

    public static class UserInfo {
        public final String name;
        public final String email;
        public final String role;

        public UserInfo(String name, String email, String role) {
            this.name = name;
            this.email = email;
            this.role = role;
        }
    }
}
