package tech.easyflow.datacenter.integration;

import org.springframework.stereotype.Component;
import tech.easyflow.datacenter.execution.model.DatacenterQueryRequest;
import tech.easyflow.datacenter.execution.model.DatacenterSchemaResponse;
import tech.easyflow.datacenter.execution.service.DatacenterDatasetQueryService;
import tech.easyflow.datacenter.meta.entity.DatacenterDatasetVersion;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;

@Component
public class DefaultAssistantDatacenterBridge implements AssistantDatacenterBridge {

    @Resource
    private DatacenterDatasetQueryService queryService;

    @Override
    public AssistantDatacenterResult queryPage(DatacenterQueryRequest request) {
        var page = queryService.queryPage(request);
        DatacenterSchemaResponse schema = queryService.getSchema(request.getDatasetRef());
        AssistantDatacenterResult result = new AssistantDatacenterResult();
        result.setRows(page.getRecords());
        result.setSource(schema.getSource());
        result.setCatalog(schema.getCatalog());
        result.setTable(schema.getTable());
        result.setVersion(resolveVersion(schema.getVersions(), request == null || request.getDatasetRef() == null ? null : request.getDatasetRef().getVersionId()));
        result.setQuerySummary(new LinkedHashMap<>() {{
            put("pageNumber", page.getPageNumber());
            put("pageSize", page.getPageSize());
            put("totalRows", page.getTotalRow());
            put("selectedColumns", request == null ? List.of() : request.getSelectedColumns());
            put("filterCount", request == null || request.getFilters() == null ? 0 : request.getFilters().size());
            put("sortCount", request == null || request.getSorts() == null ? 0 : request.getSorts().size());
        }});
        return result;
    }

    private DatacenterDatasetVersion resolveVersion(List<DatacenterDatasetVersion> versions, java.math.BigInteger versionId) {
        if (versions == null || versions.isEmpty()) {
            return null;
        }
        if (versionId == null) {
            return versions.get(0);
        }
        return versions.stream().filter(version -> versionId.equals(version.getId())).findFirst().orElse(null);
    }
}
