package at.procon.dip.embedding.service;

import at.procon.dip.embedding.job.service.EmbeddingJobService;
import at.procon.dip.embedding.model.EmbeddingPrefixMode;
import at.procon.dip.embedding.model.EmbeddingProviderResult;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class EmbeddingJobExecutionPersistenceService {

    private final EmbeddingPersistenceService embeddingPersistenceService;
    private final EmbeddingJobService jobService;

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public UUID startProcessing(UUID representationId, String modelKey) {
        var embedding = embeddingPersistenceService.ensurePending(representationId, modelKey);
        embeddingPersistenceService.markProcessing(embedding.getId());
        return embedding.getId();
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void completeJob(UUID embeddingId,
                            EmbeddingProviderResult result,
                            UUID jobId,
                            String providerRequestId) {
        embeddingPersistenceService.saveCompleted(embeddingId, result);
        jobService.markCompleted(jobId, providerRequestId);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void completeJob(UUID embeddingId,
                            float[] vector,
                            Integer tokenCount,
                            UUID jobId,
                            String providerRequestId) {
        completeJob(embeddingId, vector, tokenCount, jobId, providerRequestId, EmbeddingPrefixMode.OFF, null);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void completeJob(UUID embeddingId,
                            float[] vector,
                            Integer tokenCount,
                            UUID jobId,
                            String providerRequestId,
                            EmbeddingPrefixMode prefixMode,
                            String appliedPrefix) {
        embeddingPersistenceService.saveCompleted(embeddingId, vector, tokenCount, prefixMode, appliedPrefix);
        jobService.markCompleted(jobId, providerRequestId);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void failJob(UUID embeddingId,
                        UUID jobId,
                        String errorMessage,
                        boolean retryable) {
        embeddingPersistenceService.markFailed(embeddingId, errorMessage);
        jobService.markFailed(jobId, errorMessage, retryable);
    }
}
