package com.cameleer.server.app.storage;

import com.cameleer.server.core.admin.ThresholdConfig;
import com.cameleer.server.core.admin.ThresholdRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public class PostgresThresholdRepository implements ThresholdRepository {

    private final JdbcTemplate jdbc;
    private final ObjectMapper objectMapper;

    public PostgresThresholdRepository(JdbcTemplate jdbc, ObjectMapper objectMapper) {
        this.jdbc = jdbc;
        this.objectMapper = objectMapper;
    }

    @Override
    public Optional<ThresholdConfig> find() {
        List<ThresholdConfig> results = jdbc.query(
                "SELECT config_val FROM server_config WHERE config_key = 'thresholds'",
                (rs, rowNum) -> {
                    String json = rs.getString("config_val");
                    try {
                        return objectMapper.readValue(json, ThresholdConfig.class);
                    } catch (JsonProcessingException e) {
                        throw new RuntimeException("Failed to deserialize threshold config", e);
                    }
                });
        return results.isEmpty() ? Optional.empty() : Optional.of(results.get(0));
    }

    @Override
    public void save(ThresholdConfig config, String updatedBy) {
        String json;
        try {
            json = objectMapper.writeValueAsString(config);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to serialize threshold config", e);
        }

        jdbc.update("""
                INSERT INTO server_config (config_key, config_val, updated_by, updated_at)
                VALUES ('thresholds', ?::jsonb, ?, now())
                ON CONFLICT (config_key) DO UPDATE SET
                    config_val = EXCLUDED.config_val,
                    updated_by = EXCLUDED.updated_by,
                    updated_at = now()
                """,
                json, updatedBy);
    }
}
