package dev.dinauer.maven.maven.core;

import dev.dinauer.maven.jpa.events.Event;
import dev.dinauer.maven.jpa.events.EventType;
import dev.dinauer.maven.jpa.events.Resource;
import dev.dinauer.maven.jpa.events.repo.EventRepo;
import dev.dinauer.maven.jpa.maven.ArtifactId;
import dev.dinauer.maven.jpa.maven.Version;
import dev.dinauer.maven.jpa.maven.repo.VersionRepo;
import dev.dinauer.maven.maven.token.TokenService;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;

import java.time.ZonedDateTime;
import java.util.Optional;

@ApplicationScoped
public class VersionService
{
    @Inject
    VersionRepo versionRepo;

    @Inject
    ArtifactService artifactService;

    @Inject
    EventRepo eventRepo;

    @Inject
    TokenService tokenService;

    public Optional<Version> findOptional(String groupId, String artifactId, String version)
    {
        return versionRepo.findOptionalByVersion(groupId, artifactId, version);
    }

    public Version findOrCreate(String groupId, String artifactId, String version)
    {
        Optional<Version> versionOptional = versionRepo.findOptionalByVersion(groupId, artifactId, version);
        if (versionOptional.isPresent())
        {
            return versionOptional.get();
        }
        else
        {
            ArtifactId artifact = artifactService.findOrCreate(groupId, artifactId);
            artifact.setUpdatedAt(ZonedDateTime.now());
            return new Version().setVersion(version).setArtifact(artifact).setGroupId(groupId).setArtifactId(artifactId);
        }
    }

    public void persist(Version version)
    {
        versionRepo.persist(version);
        eventRepo.persist(new Event().setAccountId(tokenService.require()).setType(EventType.UPLOAD).setResource(new Resource().setGroupId(version.getGroupId()).setArtifactId(version.getArtifactId()).setVersion(version.getVersion())).setTimestamp(ZonedDateTime.now()));
    }
}