using Hcs.WebApp.Data.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Radzen;
using System.Security.Claims;

namespace Hcs.WebApp.Controllers
{
    [Route("identity/")]
    [Authorize]
    public class IdentityController(
        UserManager<AppUser> userManager,
        SignInManager<AppUser> signInManager) : Controller
    {
        private readonly UserManager<AppUser> userManager = userManager;
        private readonly SignInManager<AppUser> signInManager = signInManager;

        [HttpPost]
        [Route("login")]
        [AllowAnonymous]
        public async Task<IActionResult> Login(string userName, string password, string returnUrl)
        {
            var result = await signInManager.PasswordSignInAsync(userName, password, false, false);
            if (!result.Succeeded)
            {
                if (!string.IsNullOrEmpty(returnUrl))
                {
                    return Redirect($"/account/login?status=failed&returnUrl={Uri.EscapeDataString(returnUrl)}");
                }
                else
                {
                    return Redirect($"/account/login?status=failed");
                }
            }

            if (string.IsNullOrEmpty(returnUrl))
            {
                return Redirect("/");
            }

            return Redirect(returnUrl);
        }

        [HttpGet]
        [Route("logout")]
        public async Task<IActionResult> Logout()
        {
            await signInManager.SignOutAsync();

            return Redirect("/");
        }

        [HttpPost]
        [Route("change-password")]
        public async Task<IActionResult> ChangePassword(string oldPassword, string newPassword)
        {
            var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            var user = await userManager.FindByIdAsync(userId);

            var isPasswordCorrect = await userManager.CheckPasswordAsync(user, oldPassword);
            if (!isPasswordCorrect)
            {
                return BadRequest("Неверный текущий пароль");
            }

            var result = await userManager.ChangePasswordAsync(user, oldPassword, newPassword);
            if (result.Succeeded)
            {
                return Ok();
            }

            var message = string.Join(", ", result.Errors.Select(x => x.Description));
            return BadRequest(message);
        }
    }
}
