package com.ga.api.service.commission;

import com.ga.core.mapper.commission.AgentGradeEvaluationMapper;
import com.ga.core.mapper.commission.GradeEvalRuleMapper;
import com.ga.core.vo.commission.AgentGradeEvaluationSaveReq;
import com.ga.core.vo.commission.AgentGradeEvaluationVO;
import com.ga.core.vo.commission.GradeEvalRuleVO;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.math.BigDecimal;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class GradeEvaluationServiceTest {

    @Mock GradeEvalRuleMapper ruleMapper;
    @Mock AgentGradeEvaluationMapper evalMapper;

    @InjectMocks GradeEvaluationService service;

    @Test
    @DisplayName("createEval: 매칭 룰이 있으면 evaluated_grade_id = rule.gradeId")
    void createEval_ruleMatched() {
        GradeEvalRuleVO rule = new GradeEvalRuleVO();
        rule.setGradeId(5L);
        when(ruleMapper.selectActiveRuleByScore(any(), any())).thenReturn(rule);

        AgentGradeEvaluationSaveReq req = new AgentGradeEvaluationSaveReq();
        req.setAgentId(1L);
        req.setEvalPeriod("202506");
        req.setPerformanceScore(new BigDecimal("850"));
        req.setPrevGradeId(3L);

        ArgumentCaptor<AgentGradeEvaluationVO> captor = ArgumentCaptor.forClass(AgentGradeEvaluationVO.class);
        when(evalMapper.insert(captor.capture())).thenReturn(1);

        service.createEval(req);

        AgentGradeEvaluationVO saved = captor.getValue();
        assertThat(saved.getEvaluatedGradeId()).isEqualTo(5L);
        assertThat(saved.getStatus()).isEqualTo("EVALUATED");
    }

    @Test
    @DisplayName("createEval: 매칭 룰 없으면 evaluated_grade_id = prevGradeId 유지")
    void createEval_noRuleMatch_usePrevGrade() {
        when(ruleMapper.selectActiveRuleByScore(any(), any())).thenReturn(null);

        AgentGradeEvaluationSaveReq req = new AgentGradeEvaluationSaveReq();
        req.setAgentId(1L);
        req.setEvalPeriod("202506");
        req.setPerformanceScore(new BigDecimal("100"));
        req.setPrevGradeId(2L);

        ArgumentCaptor<AgentGradeEvaluationVO> captor = ArgumentCaptor.forClass(AgentGradeEvaluationVO.class);
        when(evalMapper.insert(captor.capture())).thenReturn(1);

        service.createEval(req);

        AgentGradeEvaluationVO saved = captor.getValue();
        assertThat(saved.getEvaluatedGradeId()).isEqualTo(2L);
    }
}
