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

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


        [HttpGet]
        public override async Task<IActionResult> GetAll()
        {
            try
            {
                using (var context = tsGestionAntifraude.NuevoContexto(SoloLectura: true, UseLazyLoadingProxies: false))
                {
                    var entities = await context.NOMINAS
                     .Include(x => x.IDTIPONavigation)
                     .Include(x => x.IDSITUACIONNOMINANavigation)
                        .AsNoTracking()
                        .ToListAsync();
                    //.Include(v => v.IDSERVICIOADSCRITONavigation)
                    //.Include(v => v.IDUNIDADADMINISTRATIVANavigation)
                    return Ok(entities);
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"Error interno del servidor: {ex.Message}");
            }
        }

        [Authorize(Policy = "LecturaPolicy")]
        [HttpGet("{id}")]
        public override IActionResult GetById(int id)
        {
            try
            {
                using (var context = tsGestionAntifraude.NuevoContexto(SoloLectura: true, UseLazyLoadingProxies: false))
                {
                    //var dbSet = context.Set<VIDA_ADMINISTRATIVA>();
                    var entities = context.NOMINAS
                                         .Include(x => x.IDTIPONavigation)
                     .Include(x => x.IDSITUACIONNOMINANavigation)
                     //.Include(x => x.NOMINATRABAJADORCABECERA)
                     //.ThenInclude(pr => pr.IDPERSONANavigation)
                        .AsNoTracking()
                        .FirstOrDefault(v => v.IDNOMINAS == id);



                    if (entities == null)
                        return NotFound();

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


        [Authorize(Policy = "LecturaPolicy")]
        [HttpPost("filtrar")] // Cambié a POST ya que estás usando [FromBody]
        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<NOMINAS, bool>>;
                    if (deserializedExpression == null)
                    {
                        return BadRequest("La expresión deserializada es nula o incorrecta.");
                    }
                    var entities = await context.NOMINAS.Where(deserializedExpression)
                                           //.Include(m => m.IDMOTIVOADMINISTRATIVONavigation)
                                           //.ThenInclude(aa => aa.IDTIPOAPTOSNavigation)
                                           .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}");
            }
        }
    }
}
