package com.dacrt.SBIABackend.service;

import java.math.BigDecimal;
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.ZoneId;
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 com.dacrt.SBIABackend.dto.GlobalSectionDto;
import com.dacrt.SBIABackend.dto.RiesgosGeneralesDto;
import com.dacrt.SBIABackend.security.dto.RespuestaDto;

@Service
public class RiskGeneralService {
	Logger logger = LoggerFactory.getLogger(RiskGeneralService.class);
	
	@PersistenceContext
	private EntityManager entityManager;
	
	public RiskGeneralService() {
		super();
		
	}

	public GlobalSectionDto getRiskGeneral(LocalDate from,LocalDate to) throws ParseException {
		RespuestaDto respuesta = new RespuestaDto("", false);
		HttpStatus estatus = HttpStatus.FORBIDDEN;
		long cuantosregistro;
		GlobalSectionDto riesgosGeneralesDto=new GlobalSectionDto();   
		// 1. Procesamos el 'from' (Año-Mes-Día) -> "2025-01-01"
	    
		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=1  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());
			    }
			}
			
			riesgosGeneralesDto.setLabel("Riesgos Identificados");
			riesgosGeneralesDto.setValue(conteo);
		    return riesgosGeneralesDto;	    	 
	    }catch (Exception e) {
			respuesta = new RespuestaDto("Error interno del servidor: "+e.getMessage(), false);
			estatus = HttpStatus.INTERNAL_SERVER_ERROR;
			return riesgosGeneralesDto;
		} finally {
			if (entityManager != null && entityManager.isOpen()) {
				entityManager.close();
			}
		}					
					
	 	}

}
