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

import dev.dinauer.maven.maven.core.context.ReleaseContext;
import dev.dinauer.maven.maven.core.context.SnapshotContext;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;

@ApplicationScoped
public class SnapshotService
{
    @Inject
    SnapshotPomService snapshotPomService;

    @Inject
    SnapshotJarService snapshotJarService;

    @Transactional
    public void upload(SnapshotContext snapshotContext, byte[] content)
    {
        switch (snapshotContext.extensions().ext())
        {
            case JAR ->
            {
                snapshotJarService.store(snapshotContext, content);
            }
            case POM ->
            {
                snapshotPomService.store(snapshotContext, content);
            }
        }
    }

    public Response serve(SnapshotContext snapshotContext)
    {
        switch (snapshotContext.extensions().ext())
        {
            case JAR ->
            {
                if (snapshotContext.extensions().hashExt().isEmpty())
                {
                    return Response.status(200).type(MediaType.APPLICATION_OCTET_STREAM).entity(snapshotJarService.find(snapshotContext)).build();
                }
                else
                {
                    return Response.status(200).type(MediaType.TEXT_PLAIN).entity(snapshotJarService.findHash(snapshotContext)).build();
                }
            }
            case POM ->
            {
                if (snapshotContext.extensions().hashExt().isEmpty())
                {
                    return Response.status(200).type(MediaType.APPLICATION_XML).entity(snapshotPomService.find(snapshotContext)).build();
                }
                else
                {
                    return Response.status(200).type(MediaType.TEXT_PLAIN).entity(snapshotPomService.findHash(snapshotContext)).build();
                }
            }
        }
        throw new BadRequestException();
    }
}