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 ACTOSADMINPREPController : GenericoController<ACTOSADMINPREP, int>
    {
        public ACTOSADMINPREPController()
            : base()
        {
        }

        [Authorize(Policy = "LecturaPolicy")]
        [HttpGet("MotivosExtend/{idActo}")]
        public async Task<IActionResult> TiposExtend(int idActo)
        {
            try
            {
                using (var context = tsGestionAntifraude.NuevoContexto(SoloLectura: true, UseLazyLoadingProxies: false))
                {
                    var motAdmin = context.ACTOSADMINPREP.Include(v => v.IDMOTIVOADMINISTRATIVONavigation).Include(v => v.IDMOTIVOADMINISTRATIVONavigation.IDTIPOAPTOSNavigation).FirstOrDefault(p => p.IDACTOADMINISTRATIVO == idActo);
                    if (motAdmin == null)
                        return NotFound();

                    return Ok(motAdmin);
                }
            }
            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<ACTOSADMINPREP, bool>>;
                    if (deserializedExpression == null)
                    {
                        return BadRequest("La expresión deserializada es nula o incorrecta.");
                    }
                    var entities = await context.ACTOSADMINPREP.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}");
            }
        }
    }
}
