using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Serilog;
using WorkFlowCheck.Common.DTO;
using WorkFlowCheck.Web.Services;
using WorkFlowCheck.Web.Services.Interfaces;

namespace WorkFlowCheck.Web.Pages.UserAndRole
{
    public class UserEditPageModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        private readonly IUserService _userService;

        [BindProperty]
        public UserDTO UserDTO { get; set; }

        public UserEditPageModel(ILogger<IndexModel> logger, IUserService userService)
        {
            _userService = userService;
            _logger = logger;
        }

        public async Task OnGet(int id)
        {
            UserDTO = await _userService.GetUser(id);
        }
        public async Task<IActionResult> OnPostSave([FromBody] UserDTO userDTO)
        {
            try
            {
                var result = await _userService.UpdateUser(userDTO);
                if (result.IsSuccess)
                {
                    return new JsonResult(new { success = true });
                }
                else
                {
                    return new JsonResult(new { success = false });
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }

            return new JsonResult(new { success = false });
        }
        public async Task<JsonResult> OnGetLoadRoles(int id)
        {
            UserDTO = await _userService.GetUser(id);
            return new JsonResult(new { data = UserDTO.RoleDTO });
        }
    }
}
