package com.easyagents.federation.sql.source;

import java.util.Objects;
import javax.sql.DataSource;

/**
 * 创建共享或独占 DataSource Handle 的便捷方法。
 */
public final class FederationDataSourceHandles {

    private FederationDataSourceHandles() {
    }

    /**
     * 创建不关闭底层共享池的 Handle。
     *
     * @param dataSource 共享 DataSource
     * @param fingerprint 运行指纹
     * @return 共享 Handle
     */
    public static FederationDataSourceHandle shared(
        DataSource dataSource,
        RuntimeFingerprint fingerprint
    ) {
        return owned(dataSource, fingerprint, () -> { });
    }

    /**
     * 创建关闭时执行指定回调的独占 Handle。
     *
     * @param dataSource DataSource 或连接池
     * @param fingerprint 运行指纹
     * @param closeAction 独占资源关闭动作
     * @return 独占 Handle
     */
    public static FederationDataSourceHandle owned(
        DataSource dataSource,
        RuntimeFingerprint fingerprint,
        Runnable closeAction
    ) {
        Objects.requireNonNull(dataSource, "dataSource must not be null");
        Objects.requireNonNull(fingerprint, "fingerprint must not be null");
        Objects.requireNonNull(closeAction, "closeAction must not be null");
        return new FederationDataSourceHandle() {
            private boolean closed;

            @Override
            public DataSource dataSource() {
                return dataSource;
            }

            @Override
            public RuntimeFingerprint fingerprint() {
                return fingerprint;
            }

            @Override
            public synchronized void close() {
                if (closed) {
                    return;
                }
                // 仅在底层资源确实释放后提交关闭状态，允许瞬时失败后安全重试。
                closeAction.run();
                closed = true;
            }
        };
    }
}
