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

import dev.dinauer.maven.event.Event;
import dev.dinauer.maven.event.EventType;
import dev.dinauer.maven.event.Resource;
import dev.dinauer.maven.event.repo.EventRepo;
import dev.dinauer.maven.maven.core.context.ReleaseContext;
import dev.dinauer.maven.maven.core.context.SnapshotContext;
import dev.dinauer.maven.maven.core.model.FileHash;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.WebApplicationException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.NotImplementedException;

import java.nio.charset.StandardCharsets;
import java.time.ZonedDateTime;

@ApplicationScoped
public class ReleasePomService
{
    @Inject
    ReleasePomRepo releasePomRepo;

    @Inject
    ReleaseVersionService releaseVersionService;
    @Inject
    EventRepo eventRepo;

    public void store(ReleaseContext releaseContext, byte[] body)
    {
        ReleasePom jar = releasePomRepo.find(releaseContext);
        if (jar == null)
        {
            create(releaseContext, body);
            createEvent(releaseContext);
        }
        else
        {
            throw new WebApplicationException(409);
        }
    }

    public String find(ReleaseContext releaseContext)
    {
        return releasePomRepo.require(releaseContext).getPom();
    }

    public String findHash(ReleaseContext releaseContext)
    {
        ReleasePom releasePom = releasePomRepo.require(releaseContext);
        return switch (releaseContext.extensions().hashExt().orElseThrow())
        {
            case MD5 -> releasePom.getMd5();
            case SHA1 -> releasePom.getSha1();
            default -> throw new IllegalStateException("Unexpected value: " + releaseContext.extensions().hashExt());
        };
    }

    private void create(ReleaseContext releaseContext, byte[] content)
    {
        ReleasePom releasePom = new ReleasePom();
        releasePom.setReleaseVersion(releaseVersionService.findOrCreate(releaseContext));
        releasePom.setPom(new String(content, StandardCharsets.UTF_8));
        releasePom.setMd5(DigestUtils.md5Hex(content));
        releasePom.setSha1(DigestUtils.sha1Hex(content));
        releasePom.setFilename(releaseContext.filename());
        releasePomRepo.persist(releasePom);
    }

    private void createEvent(ReleaseContext releaseContext)
    {
        eventRepo.persist(new Event().setType(EventType.UPLOAD).setTimestamp(ZonedDateTime.now()).setResource(new Resource().setGroupId(releaseContext.groupId()).setArtifactId(releaseContext.artifactId()).setVersion(releaseContext.version()).setSnapshot(false)));
    }
}
