using FluentValidation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json.Linq;
using System.IdentityModel.Tokens.Jwt;
using System.Runtime.Intrinsics.Arm;
using System.Text;
using VentaUniformes.Application.Exceptions;
using VentaUniformes.Application.Features;
using VentaUniformes.Application.Interfaces.External;
using VentaUniformes.Application.Sesion.Commands.CreateSesion;
using VentaUniformes.Application.VentasView;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Model;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace VentaUniformes.app.Controllers
{
    [TypeFilter(typeof(ExceptionManager))]//captura errores de todo el controller 
    public class SesionController : Controller
    {
        private readonly ICreateSesionCommand createSesionCommand;
        private readonly IValidator<InCreateSesionModel> validador;
        private readonly IConfiguration config; 
        private readonly IValidateTokenService _tokenValidator;

        private readonly IVentasViewService ventasViewService;

        public SesionController(ICreateSesionCommand _createSesionCommand,
                                IValidator<InCreateSesionModel> _validador,
                                IConfiguration _config,
                                 IValidateTokenService tokenValidator,
                                 IVentasViewService _ventasViewService
                                )
        {
            ventasViewService = _ventasViewService;
            createSesionCommand = _createSesionCommand;
            validador = _validador;
            this.config = _config;
            _tokenValidator= tokenValidator;
        }

        [AllowAnonymous]
        [HttpGet]
        public IActionResult Login()
        {
            var token = Request.Cookies["JwtToken"];
            if (token!=null && !_tokenValidator.ValidateToken(token))
            {
               return RedirectToAction("Logout", "Sesion");
            }
            else if(token != null)
            {
                return RedirectToAction("Principal", "Venta");
            }
            return View();
        }
       


        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Login( InCreateSesionModel model)
        {
           // ViewData["Mensaje"] = null;
            //ViewData["JwtToken"] = "";
            var validacion = await validador.ValidateAsync(model);
            if (!validacion.IsValid)
            {
                ModelState.AddModelError("", validacion.ToString());
                return View(model);

            }
            var data = await createSesionCommand.Execute(model);
            if(data==null || data.UserId<0)
            {
                ViewData["Mensaje"] = "Usuario o contraseña incorrectos.";
                return View(model);
            }
            // Guardar el token en una cookie
            var cookieOptions = new CookieOptions
            {
                HttpOnly = true,  // Evita el acceso por JavaScript
                Secure = true,    // Solo se enviará a través de HTTPS
                Expires = DateTimeOffset.UtcNow.AddMinutes(int.Parse(config["TimeLogin"])) // Tiempo de expiración
            };

            Response.Cookies.Append("JwtToken", data.Token, cookieOptions);
            Response.Cookies.Append("UserName", model.UserName, cookieOptions);
            Response.Cookies.Append("UserRole", data.Role.ToString(), cookieOptions);

            // ViewData["URLbase"] = config["URLbase"];
            //ViewData["JwtToken"] = data.Token; // Pasar el token a la vista
            //return View(model);
            return RedirectToAction("Principal", "Venta");

        }

        [AllowAnonymous]
        [HttpGet]
        public IActionResult Logout()
        {
            Response.Cookies.Delete("JwtToken");
            Response.Cookies.Delete("UserName");
            Response.Cookies.Delete("UserRole");
            return RedirectToAction("", "Sesion");
        }

    }
}
