package infrastructure.adapter.output.persistence;

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.entity.AppConfiguration;
import domain.model.Configuration;
import domain.repository.AppConfigRepository;
import io.agroal.api.AgroalDataSource;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.util.Optional;

@ApplicationScoped
public class AppConfigRepositoryAdapter implements AppConfigRepository {

    @Inject
    AgroalDataSource dataSource;

    @Inject
    ObjectMapper objectMapper;

    @Override
    public Optional<AppConfiguration> findConfigByAppName(String appName) {
        String sql = "SELECT * FROM get_application_config(?)";

        try (var conn = dataSource.getConnection();
             var ps = conn.prepareStatement(sql)) {

            ps.setString(1, appName);

            try (var rs = ps.executeQuery()) {
                if (rs.next()) {
                    var config = new AppConfiguration();

                    config.setAppId(rs.getLong("id_appconfig"));
                    config.setAppName(rs.getString("app_name"));
                    config.setApiName(rs.getString("api_name"));
                    config.setType(rs.getString("type"));
                    config.setEvent(rs.getString("event"));
                    config.setEncryptionData(rs.getBoolean("encryption_data"));
                    var jsonString = rs.getString("configuration");
                    if (jsonString != null) {
                        config.setConfiguration(objectMapper.readValue(jsonString, Configuration.class));
                    }

                    return Optional.of(config);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Error al llamar a get_application_config", e);
        }
        return Optional.empty();
    }
}