package dev.dinauer.maven.maven.core;

import dev.dinauer.maven.jpa.maven.ArtifactId;
import dev.dinauer.maven.jpa.maven.GroupId;
import dev.dinauer.maven.jpa.maven.repo.ArtifactRepo;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;

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

@ApplicationScoped
public class ArtifactService
{
    @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());
            return new ArtifactId().setArtifactId(artifactId).setGroup(group).setGroupId(groupId).setCreatedAt(ZonedDateTime.now());
        }
    }

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