package dev.dinauer.maven.maven.core.snapshot;

import dev.dinauer.maven.maven.core.ArtifactId;
import dev.dinauer.maven.maven.core.ArtifactService;
import dev.dinauer.maven.maven.core.context.SnapshotContext;
import dev.dinauer.maven.maven.core.context.VersionContext;
import dev.dinauer.maven.maven.core.snapshot.metadata.utils.SnapshotComparator;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.NotFoundException;

@ApplicationScoped
public class SnapshotVersionService
{
    @Inject
    ArtifactService artifactService;

    @Inject
    SnapshotVersionRepo snapshotVersionRepo;

    public SnapshotVersion findOrCreate(VersionContext versionContext)
    {
        ArtifactId artifactId = artifactService.findOrCreate(versionContext.groupId(), versionContext.artifactId());
        SnapshotVersion snapshotVersion = snapshotVersionRepo.findByArtifactAndVersion(artifactId, versionContext.version());
        if (snapshotVersion != null)
        {
            return snapshotVersion;
        }
        else
        {
            SnapshotVersion created = new SnapshotVersion();
            created.setArtifact(artifactId);
            created.setVersion(versionContext.version());
            snapshotVersionRepo.persist(created);
            return created;
        }
    }

    public SnapshotVersion require(VersionContext versionContext)
    {
        ArtifactId artifactId = artifactService.require(versionContext.groupId(), versionContext.artifactId());
        SnapshotVersion snapshotVersion = snapshotVersionRepo.findByArtifactAndVersion(artifactId, versionContext.version());
        if (snapshotVersion != null)
        {
            return snapshotVersion;
        }
        else
        {
            throw new NotFoundException();
        }
    }
}
