using bdAntifraude.db;
using bdAntifraude.dbcontext;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Org.BouncyCastle.Asn1.Ocsp;
using Serialize.Linq.Serializers;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

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

        [HttpGet]
        public override async Task<IActionResult> GetAll()
        {
            try
            {
                using (var context = tsGestionAntifraude.NuevoContexto(SoloLectura: true, UseLazyLoadingProxies: false))
                {
                    var entities = await context.VIDA_ADMINISTRATIVA
                        .Include(v => v.IDMOTIVONavigation)
                        .ThenInclude(m => m.IDTIPOAPTOSNavigation)
                        .Include(v => v.IDPUESTONavigation)
                        .ThenInclude(x => x.IDRPTDESNavigation)
                        .ThenInclude(y => y.IDDEPARTAMENTONavigation)
                        .Include(v => v.IDTRAMOCARRERAHORIZONTALNavigation)
                        .Include(v => v.IDTIPOPERSONALNavigation)
                        .Include(v => v.NIVEL_OLDNavigation) 
                        .Include(v => v.NIVELCNavigation)
                        .Include(v => v.GRUPOTNavigation)
                        .Include(v => v.OCUPACION_OLDNavigation)
                        .Include(v => v.IDPERSONALNavigation)
                        .Include(v => v.IDPUESTONavigation)
                        .ThenInclude(n => n.IDRPTDESNavigation)
                        .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.VIDA_ADMINISTRATIVA
                    .Include(v => v.IDMOTIVONavigation)
                        .ThenInclude(m => m.IDTIPOAPTOSNavigation)
                        .Include(v => v.IDPUESTONavigation)
                         .Include(v => v.IDPERSONALNavigation)
                         .ThenInclude(x => x.IDGRUPOFUNCIONARIONavigation)
                        .Include(v => v.IDTRAMOCARRERAHORIZONTALNavigation)
                        .Include(v => v.IDTIPOPERSONALNavigation)
                        .Include(v => v.NIVEL_OLDNavigation)
                        .Include(v => v.GRUPOTNavigation)
                                                .Include(v => v.IDPUESTONavigation)
                        .ThenInclude(s => s.IDRPTDESNavigation)
                        .ThenInclude(y => y.IDDEPARTAMENTONavigation)

                        //.Include(v => v.IDSERVICIOADSCRITONavigation)
                        //.Include(v => v.IDUNIDADADMINISTRATIVANavigation)
                        .AsNoTracking()
                        .FirstOrDefault(v => v.IDVIDA == 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<VIDA_ADMINISTRATIVA, bool>>;
                    if (deserializedExpression == null)
                    {
                        return BadRequest("La expresión deserializada es nula o incorrecta.");
                    }
                    var entities = await context.VIDA_ADMINISTRATIVA.Where(deserializedExpression)
                                           .Include(v => v.IDMOTIVONavigation)
                                           .ThenInclude(m => m.IDTIPOAPTOSNavigation)
                                           .Include(v => v.IDPUESTONavigation)
                                           .Include(v => v.IDTRAMOCARRERAHORIZONTALNavigation)
                                           .Include(v => v.IDTIPOPERSONALNavigation)
                                           .Include(v => v.NIVEL_OLDNavigation)
                                           //.Include(v => v.IDSERVICIOADSCRITONavigation)
                                           //.Include(v => v.IDUNIDADADMINISTRATIVANavigation)
                                           .Include(v => v.NIVELCNavigation)
                                           .Include(v => v.GRUPOTNavigation)
                                           .Include(v => v.OCUPACION_OLDNavigation)
                                           .Include(v => v.IDPERSONALNavigation)
                                           .Include(v => v.IDPUESTONavigation)
                                           .ThenInclude(n => n.IDRPTDESNavigation)
                                           .ThenInclude(gr => gr.GRUPO1Navigation)
                                            .Include(v => v.IDPUESTONavigation)
                                           .ThenInclude(n => n.IDRPTDESNavigation)
                                           .ThenInclude(x => x.IDDEPARTAMENTONavigation)
                                           .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("puestospersona/{idPersona}")]
        public async Task<IActionResult> PuestosPersona(int idPersona)
        {
            try
            {
                using (var context = tsGestionAntifraude.NuevoContexto(SoloLectura: true, UseLazyLoadingProxies: false))
                {
                    var entities = bdAntifraude.Utilidades.ObtienePuestoPersona(context,idPersona);

                    // 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("vidaspersona/{idPersona}")]
        public async Task<IActionResult> VidasPersona(int idPersona)
        {
            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<VIDA_ADMINISTRATIVA, bool>>;
                    //if (deserializedExpression == null)
                    //{
                    //    return BadRequest("La expresión deserializada es nula o incorrecta.");
                    //}
                    var entities = await context.VIDA_ADMINISTRATIVA.Where(x => x.IDPERSONAL == idPersona)
                                           .Include(v => v.IDMOTIVONavigation)
                                           .ThenInclude(m => m.IDTIPOAPTOSNavigation)
                                           .Include(v => v.IDPUESTONavigation)
                                           .Include(v => v.IDTRAMOCARRERAHORIZONTALNavigation)
                                           .Include(v => v.IDTIPOPERSONALNavigation)
                                           .Include(v => v.NIVEL_OLDNavigation)
                                           //.Include(v => v.IDSERVICIOADSCRITONavigation)
                                           //.Include(v => v.IDUNIDADADMINISTRATIVANavigation)
                                           .Include(v => v.NIVELCNavigation)
                                           .Include(v => v.GRUPOTNavigation)
                                           .Include(v => v.LINEASVIDAADMINISTRATIVA)
                                           .Include(v => v.OCUPACION_OLDNavigation)
                                           .Include(v => v.IDPERSONALNavigation)
                                           .Include(v => v.IDPUESTONavigation)
                                           .ThenInclude(n => n.IDRPTDESNavigation)
                                           .ThenInclude(x => x.IDDEPARTAMENTONavigation)
                                           .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}");
            }
        }
    }
}
