package com.ga.external.bank;

import com.ga.common.adapter.bank.BankTransferAdapter;
import com.ga.common.adapter.bank.BankTransferRequest;
import com.ga.common.adapter.bank.BankTransferResponse;
import com.ga.common.adapter.bank.BankTransferStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 펌뱅킹 Mock 구현.
 * <p>
 * 활성 조건: app.adapter.bank=mock (기본). 실제 SDK 통합 시 yml 값을 'kftc' 등으로 바꾸면 본 빈은 비활성.
 * 결과는 항상 ACCEPTED 반환. 계좌번호는 뒷 4자리 외 마스킹해 로그에 남긴다.
 */
@Slf4j
@Component
@ConditionalOnProperty(prefix = "app.adapter", name = "bank", havingValue = "mock", matchIfMissing = true)
public class MockBankTransferAdapter implements BankTransferAdapter {

    @Override
    public BankTransferResponse requestTransfer(BankTransferRequest request) {
        String masked = maskAccount(request.getAccountNo());
        String txId = "MOCK-" + UUID.randomUUID();
        log.info("[MOCK BANK] requestTransfer withdrawId={} bank={} acc={} amount={} txId={}",
                request.getWithdrawRequestId(), request.getBankCode(), masked, request.getAmount(), txId);

        return BankTransferResponse.builder()
                .txId(txId)
                .status(BankTransferStatus.ACCEPTED)
                .resultCode("0000")
                .resultMessage("MOCK accepted")
                .processedAt(LocalDateTime.now())
                .build();
    }

    @Override
    public BankTransferResponse queryStatus(String txId) {
        log.info("[MOCK BANK] queryStatus txId={}", txId);
        return BankTransferResponse.builder()
                .txId(txId)
                .status(BankTransferStatus.SETTLED)
                .resultCode("0000")
                .resultMessage("MOCK settled")
                .processedAt(LocalDateTime.now())
                .build();
    }

    private String maskAccount(String accountNo) {
        if (accountNo == null) return null;
        String digits = accountNo.replaceAll("[^0-9]", "");
        if (digits.length() <= 4) return "****";
        return "****" + digits.substring(digits.length() - 4);
    }
}
