package com.ruoyi.web.modules.booking.support;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import com.ruoyi.web.modules.farming.mapper.BizServiceAppointmentReviewMapper;
import com.ruoyi.web.modules.farming.mapper.BizTechResourceMapper;
import com.ruoyi.web.modules.farming.support.TechResourceRules;

/**
 * 根据专家全部预约评价重算 biz_tech_resource.expert_rating。
 * <p>
 * 公式：关联 review + appointment 后，对 punctuality / attitude / guidance 分别求和，三项总和再除以 3。
 */
public final class ExpertRatingRecalculator
{
    private ExpertRatingRecalculator()
    {
    }

    public static void recalculateAndUpdate(Long expertResourceId, BizServiceAppointmentReviewMapper reviewMapper,
            BizTechResourceMapper techResourceMapper)
    {
        if (expertResourceId == null)
        {
            return;
        }
        BigDecimal score = reviewMapper.selectExpertRatingScoreByProviderId(expertResourceId);
        if (score == null)
        {
            score = TechResourceRules.DEFAULT_EXPERT_RATING;
        }
        else
        {
            score = score.setScale(1, RoundingMode.HALF_UP);
        }
        techResourceMapper.updateExpertRating(expertResourceId, score);
    }

    /**
     * 为所有存在评价的专家资源重算 expert_rating。
     *
     * @return 更新条数
     */
    public static int recalculateAllWithReviews(BizServiceAppointmentReviewMapper reviewMapper,
            BizTechResourceMapper techResourceMapper)
    {
        List<Long> expertIds = reviewMapper.selectExpertProviderIdsForRatingSync();
        if (expertIds == null || expertIds.isEmpty())
        {
            return 0;
        }
        int count = 0;
        for (Long expertId : expertIds)
        {
            recalculateAndUpdate(expertId, reviewMapper, techResourceMapper);
            count++;
        }
        return count;
    }
}
