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;

/**
 * 기본 CSV 이체파일 생성기. 은행별 전용 포맷이 없을 때 사용.
 * UTF-8 BOM + 헤더 + 데이터 행.
 */
@Component
public class GenericCsvTransferGenerator implements BankTransferFileGenerator {

    private static final byte[] UTF8_BOM = new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF};

    @Override
    public String getBankCode() {
        return "GENERIC_CSV";
    }

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

    @Override
    public byte[] generate(List<PaymentVO> payments, String settleMonth) {
        StringBuilder sb = new StringBuilder();
        sb.append("정산월,은행코드,계좌번호,수취인,금액,적요\r\n");

        for (PaymentVO p : payments) {
            sb.append(csv(settleMonth)).append(",");
            sb.append(csv(p.getBankCode())).append(",");
            sb.append(csv(p.getAccountNo())).append(",");  // 이미 복호화된 값
            sb.append(csv(agentLabel(p))).append(",");
            sb.append(p.getPayAmount() != null ? p.getPayAmount().toPlainString() : "0").append(",");
            sb.append(csv("수수료 정산 " + formatMonth(settleMonth))).append("\r\n");
        }

        byte[] body = sb.toString().getBytes(StandardCharsets.UTF_8);
        byte[] result = new byte[UTF8_BOM.length + body.length];
        System.arraycopy(UTF8_BOM, 0, result, 0, UTF8_BOM.length);
        System.arraycopy(body, 0, result, UTF8_BOM.length, body.length);
        return result;
    }

    private String csv(String val) {
        if (val == null) return "";
        if (val.contains(",") || val.contains("\"") || val.contains("\n")) {
            return "\"" + val.replace("\"", "\"\"") + "\"";
        }
        return val;
    }

    private String agentLabel(PaymentVO p) {
        return p.getAgentId() != null ? "설계사#" + p.getAgentId() : "";
    }

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