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 System.IO;

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

        [Authorize(Policy = "LecturaPolicy")]
        [HttpPost("LineasVidaAdminGrid")] // Cambié a POST ya que estás usando [FromBody]
        public virtual async Task<IActionResult> LineasVidaAdminGrid([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<LINEASVIDAADMINISTRATIVA, bool>>;
                    if (deserializedExpression == null)
                    {
                        return BadRequest("La expresión deserializada es nula o incorrecta.");
                    }



                    var entities = await context.Set<LINEASVIDAADMINISTRATIVA>()
                        .Where(deserializedExpression)
                        .Include(v => v.IDVIDAADMINNavigation) // Incluyendo la navegación principal
                        .Include(v => v.IDTIPONavigation)
                        .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}");
            }
        }
        [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<PUESTOS>();
                    var entity = context.LINEASVIDAADMINISTRATIVA
                     .Include(v => v.IDVIDAADMINNavigation)
                        .ThenInclude(m => m.IDPERSONALNavigation)
                    .AsNoTracking()
                    .FirstOrDefault(v => v.IDLINEAVIDAADMIN == id);

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

                    return Ok(entity);
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"Error interno del servidor: {ex.Message}");
            }
        }
        [Authorize(Policy = "LecturaPolicy")]
        [HttpGet("LineasVidaAdminGridbyId/{idVida}")] // Cambié a POST ya que estás usando [FromBody]
        public async Task<IActionResult> LineasVidaAdminGridbyId(int idVida)
        {
            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<LINEASVIDAADMINISTRATIVA, bool>>;
                    //if (deserializedExpression == null)
                    //{
                    //    return BadRequest("La expresión deserializada es nula o incorrecta.");
                    //}



                    var entities = await context.Set<LINEASVIDAADMINISTRATIVA>()
                        .Where(x => x.IDVIDAADMIN == idVida)
                        .Include(v => v.IDVIDAADMINNavigation) // Incluyendo la navegación principal
                        .Include(v => v.IDTIPONavigation)
                        .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}");
            }
        }
    }
}
