package com.goldenchart.config;

import com.goldenchart.entity.GcAppSettings;
import com.goldenchart.repository.GcAppSettingsRepository;
import com.goldenchart.security.SecretCryptoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 기존 평문 업비트 API 키를 AES 암호문으로 일괄 변환 (1회성·멱등).
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class UpbitKeyEncryptionMigrator implements ApplicationRunner {

    private final GcAppSettingsRepository repo;
    private final SecretCryptoService secretCrypto;

    @Override
    @Transactional
    public void run(ApplicationArguments args) {
        int migrated = 0;
        for (GcAppSettings s : repo.findAll()) {
            boolean changed = false;
            String access = s.getUpbitAccessKey();
            if (access != null && !access.isBlank() && !secretCrypto.isEncrypted(access)) {
                s.setUpbitAccessKey(secretCrypto.encrypt(access));
                changed = true;
            }
            String secret = s.getUpbitSecretKey();
            if (secret != null && !secret.isBlank() && !secretCrypto.isEncrypted(secret)) {
                s.setUpbitSecretKey(secretCrypto.encrypt(secret));
                changed = true;
            }
            if (changed) {
                repo.save(s);
                migrated++;
            }
        }
        if (migrated > 0) {
            log.info("[UpbitKeyEncryptionMigrator] {} settings row(s) API keys encrypted", migrated);
        }
    }
}
