using bdAntifraude.db;
using bdAntifraude.dbcontext;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Serialize.Linq.Serializers;
using System.Linq.Expressions;

namespace SwaggerAntifraude.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class COMPLEMENTONIVELController : GenericoController<COMPLEMENTONIVEL, int>
    {
        public COMPLEMENTONIVELController()
           : base()
        {
        }

        [Authorize(Policy = "LecturaPolicy")]
        [HttpPost("filtrar2")] 
        public override async Task<IActionResult> Filtrar([FromBody] ExpressionWrapper request)
        {
            try
            {
                using (var context = tsGestionAntifraude.NuevoContexto(SoloLectura: true, UseLazyLoadingProxies: false))
                {
                    // Crear el deserializador
                    var serializer = new ExpressionSerializer(new Serialize.Linq.Serializers.JsonSerializer());

                    // Deserializar la expresión
                    var deserializedExpression = serializer.DeserializeText(request.Expression) as Expression<Func<COMPLEMENTONIVEL, bool>>;
                    if (deserializedExpression == null)
                    {
                        return BadRequest("La expresión deserializada es nula o incorrecta.");
                    }
                    var entities = await context.COMPLEMENTONIVEL.Where(deserializedExpression)
                                           .Include(v => v.IDNIVELNavigation)
                                           .AsNoTracking()
                                           .ToListAsync();

                    // Verificar si el resultado es vacío
                    if (entities.Count == 0)
                    {
                        Console.WriteLine("La consulta no devolvió resultados.");
                    }

                    return Ok(entities);
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"Error interno del servidor: {ex.Message}");
            }
        }
    }
}
