using ConstructorApp.DtoLayer.AppUserDto;
using ConstructorApp.EntityLayer.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace ConstructorAppUI.Controllers
{
    public class UserProfileController : Controller
    {
        private readonly UserManager<AppUser> _userManager;
        private readonly SignInManager<AppUser> _signInManager;

        public UserProfileController(UserManager<AppUser> userManager, SignInManager<AppUser> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }

        public async Task<IActionResult> IndexAsync()
        {
            var value = await _userManager.FindByNameAsync(User.Identity.Name);
            AppUserEditDto appUserEditDto = new AppUserEditDto()
            {
                UserName = value.UserName,
                CurrentPassword = "", // Boş bırakılabilir, formda doldurulacak
                Password = "",
                ConfirmPassword = ""
            };
            return View(appUserEditDto);
        }

        [HttpPost]
        public async Task<IActionResult> Index(AppUserEditDto appUserEditDto)
        {
            if (!ModelState.IsValid)
                return View(appUserEditDto);

            var user = await _userManager.FindByNameAsync(User.Identity.Name);

            // Şifre değiştirme talebi varsa
            if (!string.IsNullOrWhiteSpace(appUserEditDto.Password))
            {
                // Mevcut şifre boşsa veya doğrulanamazsa hata dön
                var passwordCheck = await _userManager.CheckPasswordAsync(user, appUserEditDto.CurrentPassword ?? "");
                if (!passwordCheck)
                {
                    ModelState.AddModelError(nameof(appUserEditDto.CurrentPassword), "Mevcut şifre yanlış.");
                    return View(appUserEditDto);
                }

                var result = await _userManager.ChangePasswordAsync(user, appUserEditDto.CurrentPassword, appUserEditDto.Password);
                if (!result.Succeeded)
                {
                    foreach (var error in result.Errors)
                        ModelState.AddModelError(string.Empty, error.Description);
                    return View(appUserEditDto);
                }

                // Şifre değiştikten sonra kullanıcıyı yeniden giriş yaptır
                await _signInManager.SignOutAsync();
                return RedirectToAction("Index", "Login");
            }

            // Şifre değişmemişse sadece kullanıcı adını güncelle (istersen burada kontrol koyabilirsin)
            if (user.UserName != appUserEditDto.UserName)
            {
                user.UserName = appUserEditDto.UserName;
                var updateResult = await _userManager.UpdateAsync(user);
                if (!updateResult.Succeeded)
                {
                    foreach (var error in updateResult.Errors)
                        ModelState.AddModelError(string.Empty, error.Description);
                    return View(appUserEditDto);
                }
            }

            return RedirectToAction("Index", "Dashboard");
        }
    }
}
