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

import dev.dinauer.maven.maven.core.context.SnapshotContext;
import io.quarkus.security.identity.SecurityIdentity;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.ws.rs.NotFoundException;

@ApplicationScoped
public class SnapshotBundleService
{
    @Inject
    SnapshotBundleRepo snapshotBundleRepo;

    @Inject
    SnapshotVersionService snapshotVersionService;

    @Inject
    SecurityIdentity securityIdentity;

    public SnapshotBundle findOrCreate(SnapshotContext snapshotContext)
    {
        SnapshotVersion snapshotVersion = snapshotVersionService.findOrCreate(snapshotContext);
        SnapshotBundle snapshotBundle = snapshotBundleRepo.findByVersionAndProperties(snapshotVersion, snapshotContext.date(), snapshotContext.time(), snapshotContext.buildNumber());
        if (snapshotBundle != null)
        {
            return snapshotBundle;
        }
        else
        {
            SnapshotBundle created = new SnapshotBundle();
            created.setDate(snapshotContext.date());
            created.setTime(snapshotContext.time());
            created.setBuildNumber(snapshotContext.buildNumber());
            created.setSnapshotVersion(snapshotVersion);
            created.setUploadedBy(securityIdentity.getPrincipal().getName());
            snapshotBundleRepo.persist(created);
            return created;
        }
    }

    public SnapshotBundle require(SnapshotContext snapshotContext)
    {
        SnapshotVersion snapshotVersion = snapshotVersionService.require(snapshotContext);
        SnapshotBundle snapshotBundle = snapshotBundleRepo.findByVersionAndProperties(snapshotVersion, snapshotContext.date(), snapshotContext.time(), snapshotContext.buildNumber());
        if (snapshotBundle != null)
        {
            return snapshotBundle;
        }
        else
        {
            throw new NotFoundException();
        }
    }
}
