package com.cameleer.server.app.storage;

import com.cameleer.server.core.admin.SensitiveKeysConfig;
import com.cameleer.server.core.admin.SensitiveKeysRepository;
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 PostgresSensitiveKeysRepository implements SensitiveKeysRepository {

    private final JdbcTemplate jdbc;
    private final ObjectMapper objectMapper;

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

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

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

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