package com.ga.api.transfer;

import com.ga.core.vo.settle.PaymentVO;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.List;


/**
 * KB국민은행(088) 고정폭 텍스트 이체파일 생성기.
 * 레코드 구조 (총 80바이트):
 *   은행코드(3) + 계좌번호(20) + 수취인명(20) + 금액(15, 우측정렬) + 적요(20) + CRLF(2)
 */
@Component
public class KbBankTransferGenerator implements BankTransferFileGenerator {

    private static final String BANK_CODE = "088";

    @Override
    public String getBankCode() {
        return BANK_CODE;
    }

    @Override
    public String getFileExtension() {
        return ".dat";
    }

    @Override
    public byte[] generate(List<PaymentVO> payments, String settleMonth) {
        StringBuilder sb = new StringBuilder();

        BigDecimal totalAmount = BigDecimal.ZERO;

        for (PaymentVO p : payments) {
            BigDecimal amt = p.getPayAmount() != null ? p.getPayAmount() : BigDecimal.ZERO;
            totalAmount = totalAmount.add(amt);

            sb.append(rpad(BANK_CODE, 3));
            sb.append(rpad(nvl(p.getAccountNo()), 20));  // 복호화된 계좌번호
            sb.append(rpad("설계사#" + p.getAgentId(), 20));
            sb.append(lpad(amt.longValue(), 15));
            sb.append(rpad("수수료 정산 " + formatMonth(settleMonth), 20));
            sb.append("\r\n");
        }

        // 합계 레코드
        sb.append(rpad("999", 3));
        sb.append(rpad("", 20));
        sb.append(rpad("합계", 20));
        sb.append(lpad(totalAmount.longValue(), 15));
        sb.append(rpad("TOTAL:" + payments.size() + "건", 20));
        sb.append("\r\n");

        return sb.toString().getBytes(StandardCharsets.UTF_8);
    }

    private String rpad(String val, int width) {
        if (val == null) val = "";
        if (val.length() >= width) return val.substring(0, width);
        return val + " ".repeat(width - val.length());
    }

    private String lpad(long val, int width) {
        String s = String.valueOf(val);
        if (s.length() >= width) return s.substring(s.length() - width);
        return " ".repeat(width - s.length()) + s;
    }

    private String nvl(String val) {
        return val != null ? val : "";
    }

    private String formatMonth(String settleMonth) {
        if (settleMonth != null && settleMonth.length() == 6) {
            return settleMonth.substring(0, 4) + "-" + settleMonth.substring(4, 6);
        }
        return settleMonth;
    }
}
