package dev.dinauer.maven.maven.core;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.NotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.ZonedDateTime;
import java.util.Optional;

@ApplicationScoped
public class ArtifactService
{
    private static final Logger LOG = LoggerFactory.getLogger(ArtifactService.class);

    @Inject
    ArtifactRepo artifactRepo;

    @Inject
    GroupService groupService;

    public ArtifactId findOrCreate(String groupId, String artifactId)
    {
        Optional<ArtifactId> artifactOptional = artifactRepo.findOptionalByArtifactId(groupId, artifactId);
        if (artifactOptional.isPresent())
        {
            return artifactOptional.get();
        }
        else
        {
            GroupId group = groupService.findOrCreate(groupId);
            group.setUpdatedAt(ZonedDateTime.now());

            ArtifactId created = new ArtifactId().setArtifactId(artifactId).setGroup(group).setGroupId(groupId).setCreatedAt(ZonedDateTime.now());
            artifactRepo.persist(created);
            return created;
        }
    }

    public ArtifactId require(String groupId, String artifactId)
    {
        Optional<ArtifactId> artifactOptional = artifactRepo.findOptionalByArtifactId(groupId, artifactId);
        if (artifactOptional.isPresent())
        {
            return artifactOptional.get();
        }
        else
        {
            LOG.error("Cannot find artifact {}:{}", groupId, artifactId);
            throw new NotFoundException();
        }
    }

    public Optional<ArtifactId> find(String groupId, String artifactId)
    {
        return artifactRepo.findOptionalByArtifactId(groupId, artifactId);
    }
}
