package com.ga.api.service.settle;

import com.ga.common.exception.BizException;
import com.ga.common.exception.ErrorCode;
import com.ga.common.model.PageResponse;
import com.ga.common.util.SecurityUtil;
import com.ga.core.mapper.settle.TaxInvoiceMapper;
import com.ga.core.vo.settle.TaxInvoiceResp;
import com.ga.core.vo.settle.TaxInvoiceSaveReq;
import com.ga.core.vo.settle.TaxInvoiceSearchParam;
import com.ga.core.vo.settle.TaxInvoiceVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;

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

    private final TaxInvoiceMapper taxInvoiceMapper;

    public PageResponse<TaxInvoiceResp> list(TaxInvoiceSearchParam param) {
        param.startPage();
        return PageResponse.of(taxInvoiceMapper.selectList(param));
    }

    public TaxInvoiceResp detail(Long invoiceId) {
        TaxInvoiceResp resp = taxInvoiceMapper.selectById(invoiceId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        return resp;
    }

    @Transactional
    public Long create(TaxInvoiceSaveReq req) {
        // 발행번호 중복 확인
        if (taxInvoiceMapper.selectByInvoiceNo(req.getInvoiceNo()) != null) {
            throw new BizException(ErrorCode.DUPLICATE_DATA, "이미 등록된 발행번호입니다: " + req.getInvoiceNo());
        }

        TaxInvoiceVO vo = new TaxInvoiceVO();
        vo.setInvoiceNo(req.getInvoiceNo());
        vo.setInvoiceType(req.getInvoiceType());
        vo.setIssueDate(req.getIssueDate());
        vo.setSupplyAmount(req.getSupplyAmount());
        vo.setTaxAmount(req.getTaxAmount());
        vo.setTotalAmount(req.getSupplyAmount().add(req.getTaxAmount()));
        vo.setCounterpartName(req.getCounterpartName());
        vo.setCounterpartBizNo(req.getCounterpartBizNo());
        vo.setCounterpartRep(req.getCounterpartRep());
        vo.setCounterpartAddr(req.getCounterpartAddr());
        vo.setAgentId(req.getAgentId());
        vo.setSettleMonth(req.getSettleMonth());
        vo.setSettleId(req.getSettleId());
        vo.setDescription(req.getDescription());
        vo.setIssuedBy(SecurityUtil.getCurrentUserId());
        taxInvoiceMapper.insert(vo);
        return vo.getInvoiceId();
    }

    @Transactional
    public void cancel(Long invoiceId, String cancelReason) {
        TaxInvoiceResp resp = taxInvoiceMapper.selectById(invoiceId);
        if (resp == null) throw new BizException(ErrorCode.NOT_FOUND);
        taxInvoiceMapper.cancel(invoiceId, LocalDate.now(), cancelReason);
    }
}
