package com.yeejoin.amos.boot.module.jg.biz.reminder.biz.factory;

import com.yeejoin.amos.boot.module.jg.biz.reminder.core.event.EquipCreateOrEditEvent;
import com.yeejoin.amos.boot.module.jg.biz.reminder.core.event.service.IQualityScoreUpdate;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
@RequiredArgsConstructor
public class QualityScoreUpdateFactory {
    private final List<IQualityScoreUpdate> qualityScoreUpdaters;

    private final Map<String, IQualityScoreUpdate> qualityScoreUpdaterMap = new ConcurrentHashMap<>();


    private IQualityScoreUpdate getUpdater(EquipCreateOrEditEvent.EquipType equipType) {
        return qualityScoreUpdaterMap.computeIfAbsent(equipType.name(), (k) -> {
            for (IQualityScoreUpdate qualityScoreUpdater : qualityScoreUpdaters) {
                if (qualityScoreUpdater.support(equipType)) {
                    return qualityScoreUpdater;
                }
            }
            throw new BadRequest("not found updater handler for " + equipType.name());
        });
    }

    @Async
    @Transactional(rollbackFor = Exception.class)
    public void update(EquipCreateOrEditEvent.EquipType equipType, String bizType, Set<String> recordOrPIds) {
        IQualityScoreUpdate qualityScoreUpdateHandler = getUpdater(equipType);
        qualityScoreUpdateHandler.doUpdate(bizType, recordOrPIds);
    }

}
