package com.cameleer.server.app.storage;

import com.cameleer.server.core.storage.ServerMetricsStore;
import com.cameleer.server.core.storage.model.ServerMetricSample;
import org.springframework.jdbc.core.JdbcTemplate;

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

public class ClickHouseServerMetricsStore implements ServerMetricsStore {

    private final JdbcTemplate jdbc;

    public ClickHouseServerMetricsStore(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }

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

        jdbc.batchUpdate("""
                INSERT INTO server_metrics
                    (tenant_id, collected_at, server_instance_id, metric_name,
                     metric_type, statistic, metric_value, tags)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                """,
                samples.stream().map(s -> new Object[]{
                        s.tenantId(),
                        Timestamp.from(s.collectedAt()),
                        s.serverInstanceId(),
                        s.metricName(),
                        s.metricType(),
                        s.statistic(),
                        s.value(),
                        tagsToClickHouseMap(s.tags())
                }).toList());
    }

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