package com.easyagents.federation.sql.execute;

import com.easyagents.federation.sql.source.SourceId;
import java.time.Duration;
import java.util.Comparator;
import java.util.List;
import java.util.function.BooleanSupplier;

/**
 * 单次单源或联邦查询的准入请求。
 *
 * @param sourceIds 查询实际引用的去重物理数据源，按稳定顺序排列
 * @param queryId 查询标识
 * @param timeout 最大等待时间
 * @param cancellationRequested 查询取消状态
 */
public record QueryAdmissionRequest(
    List<SourceId> sourceIds,
    QueryId queryId,
    Duration timeout,
    BooleanSupplier cancellationRequested
) {

    /**
     * 校验并创建不可变准入请求。
     */
    public QueryAdmissionRequest {
        if (sourceIds == null || sourceIds.isEmpty() || queryId == null) {
            throw new IllegalArgumentException("sourceIds and queryId must be provided");
        }
        sourceIds = sourceIds.stream()
            .distinct()
            .sorted(Comparator.comparing(SourceId::value))
            .toList();
        timeout = timeout == null ? Duration.ZERO : timeout;
        cancellationRequested = cancellationRequested == null
            ? () -> false
            : cancellationRequested;
    }

    /**
     * 返回兼容单源准入实现使用的首个数据源。
     *
     * @return 稳定排序后的首个数据源
     */
    public SourceId primarySourceId() {
        return sourceIds.get(0);
    }
}
