package dev.dinauer.maven.app;

import dev.dinauer.maven.user.User;
import dev.dinauer.maven.jpa.maven.Version;
import dev.dinauer.maven.jpa.maven.repo.ArtifactRepo;
import dev.dinauer.maven.jpa.maven.ArtifactId;
import dev.dinauer.maven.user.UserClient;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import org.eclipse.microprofile.rest.client.inject.RestClient;

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

@Path("/artifacts")
public class ArtifactResource
{
    @Inject
    ArtifactRepo artifactRepo;

    @RestClient
    UserClient userClient;

    @GET
    public List<ArtifactId> get()
    {
        return find();
    }

    @GET
    @Path("/{id}")
    public ArtifactId getById(@PathParam("id") String id)
    {
        return artifactRepo.findById(id);
    }

    private List<ArtifactId> find()
    {
        List<ArtifactId> artifactIds = artifactRepo.listAll();
        Map<String, User> accounts = getAccounts(artifactIds);
        for (ArtifactId artifactId : artifactIds)
        {
            for (Version version : artifactId.getVersions())
            {
                version.setUploadAccount(accounts.get(version.getUploadedBy()));
            }
        }
        return artifactIds;
    }

    private Map<String, User> getAccounts(List<ArtifactId> artifactIds)
    {
        List<String> ids = new ArrayList<>();
        for (ArtifactId artifactId : artifactIds)
        {
            for (Version version : artifactId.getVersions())
            {
                ids.add(version.getUploadedBy());
            }
        }

        return userClient.get(ids);
    }
}
