package dev.dinauer.maven.app;

import dev.dinauer.maven.user.User;
import dev.dinauer.maven.jpa.events.Event;
import dev.dinauer.maven.jpa.events.repo.EventRepo;
import dev.dinauer.maven.user.UserClient;
import io.quarkus.panache.common.Sort;
import io.quarkus.security.Authenticated;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.core.SecurityContext;
import org.eclipse.microprofile.rest.client.inject.RestClient;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Path("/events")
public class EventsResource
{
    @Inject
    EventRepo eventRepo;

    @RestClient
    UserClient userClient;

    @Inject
    SecurityContext context;

    @GET
    @Authenticated
    public List<Event> get()
    {
        return find(eventRepo.listAll(Sort.by("timestamp", Sort.Direction.Descending)));
    }

    private List<Event> find(List<Event> events)
    {
        Principal c = context.getUserPrincipal();
        List<String> ids = new ArrayList<>();
        for (Event event : events)
        {
            ids.add(event.getAccountId());
        }

        Map<String, User> accounts = userClient.get(ids);

        for (Event event : events)
        {
            event.setAccount(accounts.get(event.getAccountId()));
        }
        return events;
    }
}
