using Entidades.Dto;
using Modelo;
using Microsoft.AspNetCore.Mvc;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
namespace AlquilaFacil.Controllers;

[ApiController]
public class LoginController: ControllerBase
{
    [HttpPost("api/login")]
    public IActionResult Login([FromBody] LoginDto loginDto) { 
            
        if (loginDto.Email == String.Empty || loginDto.Contraseña == String.Empty) return Unauthorized(new {message = "Los Datos no llegaron correctamente o faltan"}); 
         
        var usuario = RepositorioUsuarios.Singleton.CheckUsuario(loginDto);
        if (usuario == null) return Unauthorized(new {message = "El usuario no existe o la contraseña es incorrecta"}); 

        string tokenString = GenerarToken(loginDto);
        return Ok( new {Token = tokenString, Redirect = "/Menu"});  
    }

       
    private string GenerarToken(LoginDto loginDto){
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes("ffb2cdc15d472e41a5b626e294c45020"); 
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.Name, loginDto.Email)
            }),
            Expires = DateTime.UtcNow.AddHours(1),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    }
}
