package com.ga.api.service.commission;

import com.ga.core.mapper.commission.AgentReserveFundMapper;
import com.ga.core.vo.commission.AgentReserveFundSaveReq;
import com.ga.core.vo.commission.AgentReserveFundVO;
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.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class ReserveFundServiceTest {

    @Mock AgentReserveFundMapper reserveFundMapper;

    @InjectMocks ReserveFundService service;

    @Test
    @DisplayName("create: balance = 직전월잔액 + reserveIn - reserveOut (100,000 + 50,000 - 20,000 = 130,000)")
    void create_balanceCalc() {
        AgentReserveFundVO prevMonth = new AgentReserveFundVO();
        prevMonth.setBalance(new BigDecimal("100000"));
        when(reserveFundMapper.selectLatestBefore(eq(1L), eq("202506"))).thenReturn(prevMonth);
        when(reserveFundMapper.selectByAgentAndMonth(eq(1L), eq("202506"))).thenReturn(null);

        AgentReserveFundSaveReq req = new AgentReserveFundSaveReq();
        req.setAgentId(1L);
        req.setSettleMonth("202506");
        req.setReserveIn(new BigDecimal("50000"));
        req.setReserveOut(new BigDecimal("20000"));

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

        service.create(req);

        AgentReserveFundVO saved = captor.getValue();
        assertThat(saved.getBalance()).isEqualByComparingTo("130000.00");
    }

    @Test
    @DisplayName("create: 직전월 잔액 없으면 0으로 처리 → balance = reserveIn - reserveOut")
    void create_noPrevMonth() {
        when(reserveFundMapper.selectLatestBefore(eq(1L), eq("202501"))).thenReturn(null);
        when(reserveFundMapper.selectByAgentAndMonth(eq(1L), eq("202501"))).thenReturn(null);

        AgentReserveFundSaveReq req = new AgentReserveFundSaveReq();
        req.setAgentId(1L);
        req.setSettleMonth("202501");
        req.setReserveIn(new BigDecimal("80000"));
        req.setReserveOut(new BigDecimal("30000"));

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

        service.create(req);

        AgentReserveFundVO saved = captor.getValue();
        assertThat(saved.getBalance()).isEqualByComparingTo("50000.00");
    }
}
