package com.cameleer.server.app.storage;

import com.cameleer.server.core.storage.MetricsStore;
import com.cameleer.server.core.storage.model.MetricsSnapshot;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ClickHouseMetricsStore implements MetricsStore {

    private final String tenantId;
    private final JdbcTemplate jdbc;

    public ClickHouseMetricsStore(String tenantId, JdbcTemplate jdbc) {
        this.tenantId = tenantId;
        this.jdbc = jdbc;
    }

    @Override
    public void insertBatch(List<MetricsSnapshot> snapshots) {
        if (snapshots.isEmpty()) return;

        jdbc.batchUpdate("""
                INSERT INTO agent_metrics (tenant_id, instance_id, metric_name, metric_value, tags, collected_at)
                VALUES (?, ?, ?, ?, ?, ?)
                """,
                snapshots.stream().map(s -> new Object[]{
                        tenantId,
                        s.instanceId(),
                        s.metricName(),
                        s.metricValue(),
                        tagsToClickHouseMap(s.tags()),
                        Timestamp.from(s.collectedAt())
                }).toList());
    }

    private Map<String, String> tagsToClickHouseMap(Map<String, String> tags) {
        if (tags == null || tags.isEmpty()) return new HashMap<>();
        return new HashMap<>(tags);
    }
}
