package fr.titionfire.ffsaf.data.repository;

import fr.titionfire.ffsaf.data.model.SequenceModel;
import fr.titionfire.ffsaf.utils.SequenceType;
import io.quarkus.hibernate.reactive.panache.PanacheRepositoryBase;
import io.smallrye.mutiny.Uni;
import jakarta.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class SequenceRepository implements PanacheRepositoryBase<SequenceModel, SequenceType> {

    public Uni<Long> getNextValueInTransaction(SequenceType type) {
        return this.findById(type).onItem().ifNull()
                .switchTo(() -> this.persist(new SequenceModel(type, 1L)))
                .chain(v -> {
                    v.setValue(v.getValue() + 1);
                    return this.persistAndFlush(v);
                })
                .map(SequenceModel::getValue);
    }
}
