package com.ga.api.service.receive;

import com.ga.common.util.SecurityUtil;
import com.ga.core.mapper.receive.ReceiveMapper;
import com.ga.core.vo.receive.*;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class ReceiveService {

    private final ReceiveMapper mapper;

    // === company_profile ===

    @Transactional(readOnly = true)
    public List<CompanyProfileVO> listProfiles() {
        return mapper.selectAllProfiles();
    }

    @Transactional
    public void saveProfile(String companyCode, CompanyProfileVO vo) {
        vo.setCompanyCode(companyCode);
        if (mapper.selectProfile(companyCode) == null) mapper.insertProfile(vo);
        else mapper.updateProfile(vo);
    }

    // === field_mapping ===

    @Transactional(readOnly = true)
    public List<CompanyFieldMappingVO> listFields(String companyCode, String targetTable) {
        return mapper.selectFieldMappings(companyCode, targetTable);
    }

    @Transactional
    public Long createField(String companyCode, CompanyFieldMappingVO vo) {
        vo.setCompanyCode(companyCode);
        mapper.insertFieldMapping(vo);
        return vo.getMappingId();
    }

    @Transactional
    public void updateField(Long mappingId, CompanyFieldMappingVO vo) {
        vo.setMappingId(mappingId);
        mapper.updateFieldMapping(vo);
    }

    @Transactional
    public void deleteField(Long mappingId) {
        mapper.deleteFieldMapping(mappingId);
    }

    // === code_mapping ===

    @Transactional(readOnly = true)
    public List<CodeMappingVO> listCodes(String companyCode, String codeType) {
        return mapper.selectCodeMappings(companyCode, codeType);
    }

    @Transactional
    public Long createCode(String companyCode, CodeMappingVO vo) {
        vo.setCompanyCode(companyCode);
        mapper.insertCodeMapping(vo);
        return vo.getCodeId();
    }

    // === raw + errors ===

    @Transactional(readOnly = true)
    public List<RawCommissionDataVO> listRaw(String companyCode, String settleMonth, String parseStatus) {
        return mapper.selectRawList(companyCode, settleMonth, parseStatus);
    }

    @Transactional(readOnly = true)
    public List<ParseErrorLogVO> listErrors(String companyCode, String resolveStatus) {
        return mapper.selectErrors(companyCode, resolveStatus);
    }

    @Transactional
    public void resolveError(Long errorId, String status, String note) {
        mapper.resolveError(errorId, status, note, SecurityUtil.getCurrentUserId());
    }
}
