package org.mte.numecoeval.calculs.infrastructure.repository;

import lombok.extern.slf4j.Slf4j;
import org.mte.numecoeval.calculs.domain.exception.DatabaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class DonneesEntreeRepository {

    @Autowired
    private DataSource dataSource;

    @Cacheable("DureeUsage")
    public String findDureeUsage(String nomLot, String nomOrganisation) {
        List<String> result = new ArrayList<>();
        try (Connection conn = dataSource.getConnection()) {
            try (var ps = conn.prepareStatement("""
                     SELECT duree_usage
                     FROM en_donnees_entrees
                     WHERE nom_lot = ? AND nom_organisation= ?
                    """)) {

                ps.setString(1, nomLot);
                ps.setString(2, nomOrganisation);
                var rs = ps.executeQuery();
                while (rs.next()) {
                    result.add(rs.getString("duree_usage"));
                }
            }
        } catch (SQLException e) {
            log.error("Une erreur s'est produite lors de la selection dans PostgreSQL. Exception: ", e);
            throw new DatabaseException(e);
        }
        if (result.isEmpty()) {
            return null;
        }
        return result.getFirst();
    }
}
