package jumapacelaya.gob.mx.infowall.servicio;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.stream.Collectors;

import javax.sql.DataSource;

import io.micronaut.transaction.annotation.Transactional;
import jumapacelaya.gob.mx.infowall.dto.totalPagosHoyDTO;

public class InfowallServicio {

    private final DataSource dataSource;

    public InfowallServicio(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Transactional
    public totalPagosHoyDTO obtenerTotalPagosHoy(List<Integer> entidadIds, List<Integer> puntoIds) {
        String query = "SELECT SUM(total) AS totalpagado, COUNT(total) AS numeropagos " +
                    "FROM pagosenc p " +
                    "INNER JOIN lotesenc l USING (numloteid) " +
                    "WHERE fechaing BETWEEN TRUNC(SYSDATE) AND TRUNC(SYSDATE + 1) " +
                    "AND entidadid IN (%s) AND puntoid IN (%s)";

        String entidadPlaceholders = entidadIds.stream().map(id -> "?").collect(Collectors.joining(","));
        String puntoPlaceholders = puntoIds.stream().map(id -> "?").collect(Collectors.joining(","));

        query = String.format(query, entidadPlaceholders, puntoPlaceholders);

        try (Connection connection = dataSource.getConnection();
            PreparedStatement stmt = connection.prepareStatement(query)) {

            int index = 1;
            for (Integer id : entidadIds) {
                stmt.setInt(index++, id);
            }
            for (Integer id : puntoIds) {
                stmt.setInt(index++, id);
            }

            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                BigDecimal total = rs.getBigDecimal("totalpagado");
                int count = rs.getInt("numeropagos");
                return new totalPagosHoyDTO(total != null ? total : BigDecimal.ZERO, count);
            } else {
                return new totalPagosHoyDTO(BigDecimal.ZERO, 0);
            }

        } catch (Exception e) {
            throw new RuntimeException("Error al obtener total de pagos de hoy", e);
        }
    }

}
