package com.dacrt.SBIABackend.service;

import java.math.BigInteger;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import com.dacrt.SBIABackend.dto.GlobalSectionDto;
import com.dacrt.SBIABackend.security.dto.RespuestaDto;

@Service
public class RiskGestionadosService {
	Logger logger = LoggerFactory.getLogger(RiskGestionadosService.class);
	@PersistenceContext
	private EntityManager entityManager;
	
	public RiskGestionadosService() {
		super();
		
	}
	
	public GlobalSectionDto getRiskGestionados(LocalDate from,LocalDate to) throws ParseException {
		RespuestaDto respuesta = new RespuestaDto("", false);
		HttpStatus estatus = HttpStatus.FORBIDDEN;
		long cuantosregistro;
		GlobalSectionDto riesgosGestionadosDto= new GlobalSectionDto();   

		LocalDateTime inicioDia = from.atStartOfDay(); // 2026-06-01 00:00:00
		LocalDateTime finDia = to.atTime(LocalTime.MAX);
        
	try {
			String SentenciaBase = " SELECT  count(EL.id )   "
								 + " FROM        main.riskevaluations E    "
								 + " INNER JOIN  main.riskevalfactors F    "
								 + " ON          E.id=F.riskevaluationid  AND status=0  and (E.probability!=0 and E.impact!=0)"
								 + " INNER JOIN  main.riskevalfactorelements EL    "
								 + " ON          F.id=EL.riskevalfactorid and EL.active=1 "
								 + " WHERE E.initialdate BETWEEN CAST(?1 AS timestamptz) AND CAST(?2 AS timestamptz) ";
		                         // Al poner ?1::timestamptz, Postgres recibe el texto y lo castea de inmediato
		    
		    Query query = entityManager.createNativeQuery(SentenciaBase);
		    
		    // 4. Pasamos los parámetros como String. El motor de Postgres se encargará del resto.
		    query.setParameter(1, inicioDia);
		    query.setParameter(2, finDia);
		 // Al ser un COUNT, extraemos el resultado único directamente
            Object resultado = query.getSingleResult();
			
			BigDecimal conteo = null; 
			
			if (resultado != null) {
			    if (resultado instanceof BigInteger) {
			        // ✅ Ahora sí, guardamos un BigDecimal en una variable BigDecimal
			        conteo = new BigDecimal((BigInteger) resultado);
			    } else if (resultado instanceof BigDecimal) {
			        conteo = (BigDecimal) resultado;
			    } else if (resultado instanceof Number) {
			        conteo = BigDecimal.valueOf(((Number) resultado).doubleValue());
			    }
			}
			
			riesgosGestionadosDto.setLabel("Riesgos Evaluados");
			riesgosGestionadosDto.setValue(conteo);
			
			return riesgosGestionadosDto;	    	 
	    }catch (Exception e) {
			respuesta = new RespuestaDto("Error interno del servidor: "+e.getMessage(), false);
			estatus = HttpStatus.INTERNAL_SERVER_ERROR;
			return riesgosGestionadosDto;
		} finally {
			if (entityManager != null && entityManager.isOpen()) {
				entityManager.close();
			}
		}					
					
	 	}
}
