package dev.dinauer.maven.maven.core.release;

import dev.dinauer.maven.maven.core.ArtifactService;
import dev.dinauer.maven.maven.core.context.ReleaseContext;
import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.NotFoundException;

import java.util.Map;

@ApplicationScoped
public class ReleaseJarRepo implements PanacheRepositoryBase<ReleaseJar, String>
{
    @Inject
    ReleaseVersionRepo releaseVersionRepo;

    public ReleaseJar find(ReleaseContext releaseContext)
    {
        ReleaseVersion version = releaseVersionRepo.findByGroupIdAndArtifactIdAndVersion(releaseContext.groupId(), releaseContext.artifactId(), releaseContext.version());
        if (version != null)
        {
            if (releaseContext.classifier().isPresent())
            {
                return find("releaseVersion = :version AND classifier = :classifier", Map.ofEntries(Map.entry("version", version), Map.entry("classifier", releaseContext.classifier().get()))).firstResult();
            }
            else
            {
                return find("releaseVersion = :version AND classifier IS NULL", Map.ofEntries(Map.entry("version", version))).firstResult();
            }
        }
        return null;
    }

    public ReleaseJar require(ReleaseContext releaseContext)
    {
        ReleaseVersion version = releaseVersionRepo.requireByGroupIdAndArtifactIdAndVersion(releaseContext.groupId(), releaseContext.artifactId(), releaseContext.version());
        if (version != null)
        {
            if (releaseContext.classifier().isPresent())
            {
                ReleaseJar releaseJar = find("releaseVersion = :version AND classifier = :classifier", Map.ofEntries(Map.entry("version", version), Map.entry("classifier", releaseContext.classifier().get()))).firstResult();
                if (releaseJar != null)
                {
                    return releaseJar;
                }
                throw new NotFoundException();
            }
            else
            {
                ReleaseJar releaseJar =  find("releaseVersion = :version AND classifier IS NULL", Map.ofEntries(Map.entry("version", version))).firstResult();
                if (releaseJar != null)
                {
                    return releaseJar;
                }
                throw new NotFoundException();
            }
        }
        return null;
    }
}
