package com.ga.api.service.commission;

import com.ga.common.exception.BizException;
import com.ga.common.exception.ErrorCode;
import com.ga.common.model.PageResponse;
import com.ga.core.mapper.commission.CommissionMasterMapper;
import com.ga.core.vo.commission.CommissionMasterResp;
import com.ga.core.vo.commission.CommissionMasterSearchParam;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class CommissionMasterService {

    private final CommissionMasterMapper mapper;

    public PageResponse<CommissionMasterResp> list(CommissionMasterSearchParam param) {
        param.startPage();
        return PageResponse.of(mapper.selectList(param));
    }

    public CommissionMasterResp detail(Long masterId) {
        CommissionMasterResp resp = mapper.selectById(masterId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        return resp;
    }

    public List<CommissionMasterResp> listByAgentAndMonth(Long agentId, String settleMonth) {
        return mapper.selectByAgentAndMonth(agentId, settleMonth);
    }

    public List<CommissionMasterResp> aggregatedByMonth(String settleMonth) {
        return mapper.selectAggregatedByMonth(settleMonth);
    }

    @Transactional
    public void updateStatus(Long masterId, String status) {
        CommissionMasterResp resp = mapper.selectById(masterId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        mapper.updateStatus(masterId, status);
    }

    @Transactional
    public void delete(Long masterId) {
        CommissionMasterResp resp = mapper.selectById(masterId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        mapper.delete(masterId);
    }
}
