using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using bdAntifraude.dbcontext;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;
using SwaggerAntifraude.DTOs;
using System.Linq.Dynamic.Core;
using bdAntifraude.db;
using System.Runtime.CompilerServices;
using Serialize.Linq.Serializers;
using SwaggerAntifraude.Controllers;



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

        [Authorize(Policy = "LecturaPolicy")]
        [HttpPost("filtrar")] 
        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<INCIDENCIAS, bool>>;
                    if (deserializedExpression == null)
                    {
                        return BadRequest("La expresión deserializada es nula o incorrecta.");
                    }
                    var entities = await context.INCIDENCIAS.Where(deserializedExpression)
                                           .Include(v => v.IDPERSONANavigation)
                                           
                                           .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}");
            }
        }
    }
}
