package com.ga.api.service.commission;

import com.ga.common.exception.BizException;
import com.ga.core.mapper.commission.JointContractMapper;
import com.ga.core.vo.commission.JointContractSaveReq;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class JointContractServiceTest {

    @Mock JointContractMapper jointContractMapper;

    @InjectMocks JointContractService service;

    @Test
    @DisplayName("create: 기존 지분율 합 + 신규 shareRate > 1이면 BizException 발생")
    void create_shareRateExceedsOne_throwsBizException() {
        // 기존 합 0.7, 신규 0.4 → 합계 1.1 > 1
        when(jointContractMapper.sumShareByContract(eq(100L))).thenReturn(new BigDecimal("0.7"));

        JointContractSaveReq req = new JointContractSaveReq();
        req.setContractId(100L);
        req.setAgentId(5L);
        req.setRole("MAIN");
        req.setShareRate(new BigDecimal("0.4"));

        assertThatThrownBy(() -> service.create(req))
                .isInstanceOf(BizException.class);
    }

    @Test
    @DisplayName("create: 기존 합 + 신규 shareRate <= 1이면 정상 생성")
    void create_shareRateValid_noException() {
        // 기존 합 0.6, 신규 0.4 → 합계 1.0 = 1 (경계값 허용)
        when(jointContractMapper.sumShareByContract(eq(100L))).thenReturn(new BigDecimal("0.6"));
        when(jointContractMapper.insert(org.mockito.ArgumentMatchers.any())).thenReturn(1);

        JointContractSaveReq req = new JointContractSaveReq();
        req.setContractId(100L);
        req.setAgentId(5L);
        req.setRole("SUB");
        req.setShareRate(new BigDecimal("0.4"));

        // 예외 없이 통과해야 함
        service.create(req);
    }
}
