package fr.titionfire.ffsaf.domain.service;

import fr.titionfire.ffsaf.data.model.LogModel;
import fr.titionfire.ffsaf.data.model.MembreModel;
import fr.titionfire.ffsaf.data.model.SelectionModel;
import fr.titionfire.ffsaf.data.repository.CombRepository;
import fr.titionfire.ffsaf.data.repository.SelectionRepository;
import fr.titionfire.ffsaf.rest.data.SimpleSelection;
import io.quarkus.hibernate.reactive.panache.Panache;
import io.quarkus.hibernate.reactive.panache.common.WithSession;
import io.smallrye.mutiny.Uni;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.hibernate.reactive.mutiny.Mutiny;

import java.util.List;
import java.util.function.Consumer;

@WithSession
@ApplicationScoped
public class SelectionService {

    @Inject
    CombRepository combRepository;

    @Inject
    SelectionRepository repository;

    @Inject
    LoggerService ls;

    public Uni<List<SelectionModel>> getSelection(long id, Consumer<MembreModel> checkPerm) {
        return combRepository.findById(id).invoke(checkPerm)
                .chain(combRepository -> Mutiny.fetch(combRepository.getSelections()));
    }

    public Uni<SelectionModel> setSelection(long id, SimpleSelection data) {
        if (data.getId() == -1) {
            return combRepository.findById(id).chain(membreModel -> {
                SelectionModel model = new SelectionModel();

                model.setMembre(membreModel);
                model.setSaison(data.getSaison());
                model.setCategorie(data.getCategorie());
                return Panache.withTransaction(() -> repository.persist(model))
                        .call(licenceModel -> ls.logA(LogModel.ActionType.ADD, membreModel.getObjectName(),
                                licenceModel));
            });
        } else {
            return repository.findById(data.getId()).chain(model -> {
                ls.logChange("Catégorie", model.getCategorie(), data.getCategorie(), model);
                model.setCategorie(data.getCategorie());
                return Panache.withTransaction(() -> repository.persist(model))
                        .call(__ -> ls.append());
            });
        }
    }

    public Uni<Void> deleteSelection(long id) {
        return repository.findById(id)
                .call(model -> ls.logADelete(model))
                .chain(model -> Panache.withTransaction(() -> repository.delete(model)));
    }
}
