package fr.titionfire.ffsaf.data.repository;

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

import java.util.List;

@ApplicationScoped
public class MatchRepository implements PanacheRepositoryBase<MatchModel, Long> {

    public Uni<MatchModel> create(MatchModel matchModel) {
        matchModel.setSystem(CompetitionSystem.INTERNAL);
        return Panache.withTransaction(() -> this.persistAndFlush(matchModel)
                        .invoke(matchModel1 -> matchModel1.setSystemId(matchModel1.getId())))
                .chain(this::persist);
    }

    public Uni<Void> create(List<MatchModel> matchModel) {
        if (matchModel.isEmpty())
            return Uni.createFrom().voidItem();

        matchModel.forEach(model -> model.setSystem(CompetitionSystem.INTERNAL));
        return Panache.withTransaction(() -> this.persist(matchModel)
                        .call(__ -> this.flush())
                        .invoke(__ -> matchModel.forEach(model -> model.setSystemId(model.getId())))
                        .map(__ -> matchModel))
                .chain(this::persist);
    }
}
