package com.cameleer.server.app.storage;

import com.cameleer.server.core.security.OidcConfig;
import com.cameleer.server.core.security.OidcConfigRepository;
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 PostgresOidcConfigRepository implements OidcConfigRepository {

    private final JdbcTemplate jdbc;
    private final ObjectMapper objectMapper;

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

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

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

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

    @Override
    public void delete() {
        jdbc.update("DELETE FROM server_config WHERE config_key = 'oidc'");
    }
}
