package com.easyagents.federation.sql.runtime;

import com.easyagents.federation.sql.api.FederationSqlErrorCode;
import com.easyagents.federation.sql.api.FederationSqlException;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 按逆序幂等关闭准入许可与 Runtime lease 的资源组合。
 */
final class CompositeQueryResources implements AutoCloseable {

    private final List<AutoCloseable> resources;
    private final AtomicBoolean closed = new AtomicBoolean();

    /**
     * 创建资源组合。
     *
     * @param resources 按获取顺序排列的资源
     */
    CompositeQueryResources(AutoCloseable... resources) {
        this.resources = List.of(resources);
    }

    /**
     * 逆序关闭资源并保留全部失败原因。
     */
    @Override
    public void close() {
        if (!closed.compareAndSet(false, true)) {
            return;
        }
        FederationSqlException failure = null;
        for (int index = resources.size() - 1; index >= 0; index--) {
            try {
                resources.get(index).close();
            } catch (Exception exception) {
                FederationSqlException wrapped = new FederationSqlException(
                    FederationSqlErrorCode.RESOURCE_CLOSE_FAILED,
                    "failed to close query resource",
                    exception
                );
                if (failure == null) {
                    failure = wrapped;
                } else {
                    failure.addSuppressed(wrapped);
                }
            }
        }
        if (failure != null) {
            throw failure;
        }
    }
}
