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

import dev.dinauer.maven.maven.core.context.SnapshotContext;
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 SnapshotJarRepo implements PanacheRepositoryBase<SnapshotJar, String>
{
    @Inject
    SnapshotBundleService snapshotBundleService;

    public SnapshotJar find(SnapshotContext snapshotContext)
    {
        SnapshotBundle bundle = snapshotBundleService.findOrCreate(snapshotContext);
        if (snapshotContext.classifier().isPresent())
        {
            return find("snapshotBundle = :snapshotBundle AND classifier = :classifier", Map.ofEntries(Map.entry("snapshotBundle", bundle), Map.entry("classifier", snapshotContext.classifier().get()))).firstResult();
        }
        else
        {
            return find("snapshotBundle = :snapshotBundle AND classifier IS NULL", Map.ofEntries(Map.entry("snapshotBundle", bundle))).firstResult();
        }
    }

    public SnapshotJar require(SnapshotContext snapshotContext)
    {
        SnapshotBundle bundle = snapshotBundleService.require(snapshotContext);
        if (snapshotContext.classifier().isPresent())
        {
            SnapshotJar snapshotJar = find("snapshotBundle = :snapshotBundle AND classifier = :classifier", Map.ofEntries(Map.entry("snapshotBundle", bundle), Map.entry("classifier", snapshotContext.classifier().get()))).firstResult();
            if (snapshotJar != null)
            {
                return snapshotJar;
            }
            throw new NotFoundException();
        }
        else
        {
            SnapshotJar snapshotJar = find("snapshotBundle = :snapshotBundle AND classifier IS NULL", Map.ofEntries(Map.entry("snapshotBundle", bundle))).firstResult();
            if (snapshotJar != null)
            {
                return snapshotJar;
            }
            throw new NotFoundException();
        }
    }
}
