package tech.easyflow.datacenter.connector.support;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.stereotype.Component;
import tech.easyflow.datacenter.meta.entity.DatacenterSource;
import tech.easyflow.datacenter.security.DatacenterCredentialCipher;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class DatacenterDatasourceManager {

    private final Map<BigInteger, HikariDataSource> externalDatasourceCache = new ConcurrentHashMap<>();

    @Resource
    private DatacenterCredentialCipher credentialCipher;

    public HikariDataSource createExternalDatasource(DatacenterSource source) {
        HikariConfig config = new HikariConfig();
        config.setPoolName("dc-ext-" + (source.getId() == null ? "temp" : source.getId()));
        config.setJdbcUrl(source.getJdbcUrl());
        config.setUsername(source.getUsername());
        config.setPassword(credentialCipher.decrypt(source.getCredentialCipher()));
        config.setMaximumPoolSize(3);
        config.setMinimumIdle(0);
        config.setConnectionTimeout(5000);
        config.setValidationTimeout(3000);
        if (source.getDriverClassName() != null && !source.getDriverClassName().isBlank()) {
            config.setDriverClassName(source.getDriverClassName());
        }
        return new HikariDataSource(config);
    }

    public HikariDataSource getOrCreateExternalDatasource(DatacenterSource source) {
        if (source.getId() == null) {
            return createExternalDatasource(source);
        }
        return externalDatasourceCache.computeIfAbsent(source.getId(), key -> createExternalDatasource(source));
    }
}
