package dev.dinauer.maven.maven.core;

import dev.dinauer.maven.jpa.maven.Pom;
import dev.dinauer.maven.jpa.maven.Version;
import dev.dinauer.maven.maven.core.model.MavenContext;
import dev.dinauer.maven.maven.token.TokenService;
import io.quarkus.security.identity.SecurityIdentity;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.apache.commons.codec.digest.DigestUtils;

import java.time.ZonedDateTime;

@ApplicationScoped
public class PomService
{
    @Inject
    SecurityIdentity securityIdentity;

    @Inject
    VersionService versionService;

    public Response store(MavenContext mavenContext, byte[] body)
    {
        String md5 = DigestUtils.md5Hex(body);
        String sha1 = DigestUtils.sha1Hex(body);
        Version version = versionService.findOrCreate(mavenContext.groupId(), mavenContext.artifactId(), mavenContext.version().getRaw());
        version.setUploadedBy(securityIdentity.getPrincipal().getName());
        if (version.getPom() == null)
        {
            version.setPom(new Pom().setPom(new String(body)).setMd5(md5).setSha1(sha1).setVersion(version).setUrl(mavenContext.path()).setFilename(mavenContext.file().getFilename()));
            versionService.persist(version);
            return Response.status(Response.Status.CREATED).build();
        }
        return Response.status(Response.Status.CONFLICT).build();
    }

    public Response findHash(MavenContext context)
    {
        Version version = versionService.findOptional(context.groupId(), context.artifactId(), context.version().getRaw()).orElseThrow();
        switch (context.file().getHash())
        {
            case SHA1 ->
            {
                return Response.status(Response.Status.OK).type(MediaType.TEXT_PLAIN).entity(version.getPom().getSha1()).build();
            }
            case MD5 ->
            {
                return Response.status(Response.Status.OK).type(MediaType.TEXT_PLAIN).entity(version.getPom().getMd5()).build();
            }
        }
        throw new BadRequestException();
    }

    public Response find(MavenContext mavenContext)
    {
        Version version = versionService.findOptional(mavenContext.groupId(), mavenContext.artifactId(), mavenContext.version().getRaw()).orElseThrow();
        version.setLastPulled(ZonedDateTime.now());
        version.incrementPullCount();
        return Response.status(Response.Status.OK).type(MediaType.APPLICATION_XML).entity(version.getPom().getPom()).build();
    }
}
