using System.Diagnostics;
using bitforum.Models;
using bitforum.Models.User;
using bitforum.Models.Views;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

namespace bitforum.Controllers.Director
{
    [Authorize]
    [Route("Director")]
    public class AttachController : Controller
    {
        private readonly ILogger<AttachController> _logger;
        private readonly string _ViewPath = "~/Views/Director/Attach.cshtml";
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly RoleManager<IdentityRole> _roleManager;

        public AttachController(ILogger<AttachController> logger, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
        {
            _logger = logger;
            _userManager = userManager;
            _roleManager = roleManager;
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        [HttpGet("Attach")]
        public async Task<IActionResult> Index(string userID)
        {
            var user = await _userManager.FindByIdAsync(userID);

            if (user == null)
            {
                return NotFound();
            }

            var roles = await _roleManager.Roles.ToListAsync();

            var viewModel = new AttachViewModel
            {
                UserID = user.Id,

                Roles = roles.Select(role => new CheckBoxViewModel
                {
                    DisplayValue = role.Name,
                    IsSelected = _userManager.IsInRoleAsync(user, role.Name).Result
                }).ToList()
            };

            return View(_ViewPath, viewModel);
        }

        [HttpPost]
        public async Task<IActionResult> Save(AttachViewModel request)
        {
            if (!ModelState.IsValid)
            {
                return View(_ViewPath, request);
            }

            var user = await _userManager.FindByIdAsync(request.UserID);

            if (user == null)
            {
                return NotFound();
            }

            // 회원의 역할 조회
            var userRoles = await _userManager.GetRolesAsync(user);

            // 회원의 기존 역할 제거 후 새로운 역할 추가
            /*
            await _userManager.RemoveFromRolesAsync(user, userRoles);
            await _userManager.AddToRolesAsync(user, model.Roles.Where(r => r.IsSelected).Select(r => r.DisplayValue));
            */

            foreach (var role in request.Roles)
            {
                // 현재 사용자의 역할에 포함되어 있으나 선택되지 않은 경우 해당 역할 제거
                if (userRoles.Any(r => r == role.DisplayValue) && !role.IsSelected)
                {
                    await _userManager.RemoveFromRoleAsync(user, role.DisplayValue);
                }

                // 현재 사용자의 역할에 포함되지 않았으나 선택된 경우 해당 역할 추가
                if (!userRoles.Any(r => r == role.DisplayValue) && role.IsSelected)
                {
                    await _userManager.AddToRoleAsync(user, role.DisplayValue);
                }
            }

            var message = $"역할이 정상적으로 적용되었습니다.";
            TempData["SuccessMessage"] = message;
            _logger.LogInformation(message);

            return RedirectToAction("index", "Attach", new { userId = request.UserID });
        }
    }
}
