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

import dev.dinauer.maven.maven.core.context.SnapshotContext;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.WebApplicationException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.NotImplementedException;

@ApplicationScoped
public class SnapshotJarService
{
    @Inject
    SnapshotBundleService snapshotBundleService;

    @Inject
    SnapshotJarRepo snapshotJarRepo;

    public void store(SnapshotContext snapshotContext, byte[] body)
    {
        SnapshotJar snapshotJar = snapshotJarRepo.find(snapshotContext);
        if (snapshotJar == null)
        {
            create(snapshotContext, body);
        }
        else
        {
            throw new WebApplicationException(501);
        }
    }

    public byte[] find(SnapshotContext snapshotContext)
    {
        return snapshotJarRepo.require(snapshotContext).getJar();
    }

    public String findHash(SnapshotContext snapshotContext)
    {
        switch (snapshotContext.extensions().hashExt().orElseThrow())
        {
            case SHA1 ->
            {
                return snapshotJarRepo.require(snapshotContext).getSha1();
            }
            case MD5 ->
            {
                return snapshotJarRepo.require(snapshotContext).getMd5();
            }
        }
        throw new BadRequestException();
    }

    private void create(SnapshotContext snapshotContext, byte[] content)
    {
        SnapshotJar snapshotJar = new SnapshotJar();
        snapshotJar.setSnapshotBundle(snapshotBundleService.findOrCreate(snapshotContext));
        snapshotJar.setJar(content);
        snapshotJar.setMd5(DigestUtils.md5Hex(content));
        snapshotJar.setSha1(DigestUtils.sha1Hex(content));
        snapshotJar.setClassifier(snapshotContext.classifier().orElse(null));
        snapshotJarRepo.persist(snapshotJar);
    }
}
