using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Admin.Pages.Director.User
{
    public class EditModel(IMediator mediator) : PageModel
    {
        [BindProperty]
        public GetUser.Response? Input { get; set; }

        public async Task OnGetAsync(string id, CancellationToken ct)
        {
            var user = await mediator.Send(new GetUser.Query(id), ct);

            if (user != null)
            {
                Input = new GetUser.Response
                {
                    ID = user.ID,
                    Name = user.FullName,
                    Email = user.Email,
                    Phone = user.PhoneNumber,
                    IsDeleted = user.IsDeleted,
                    EmailConfirmed = user.EmailConfirmed,
                    LockoutEnd = user.LockoutEnd.HasValue,
                    Roles = user.Roles
                };
            }
        }

        public async Task<IActionResult> OnPostAsync(CancellationToken ct)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("유효성 검사에 실패하였습니다.");
                }

                var command = new UpdateUser.Command(
                    ID: Input!.ID,
                    FullName: Input.Name,
                    Email: Input.Email,
                    NewPassword: Input.NewPassword,
                    ConfirmPassword: Input.ConfirmPassword,
                    PhoneNumber: Input.Phone,
                    IsDeleted: Input.IsDeleted,
                    EmailConfirmed: Input.EmailConfirmed,
                    LockoutEnd: Input.LockoutEnd
                );

                await mediator.Send(command, ct);

                TempData["SuccessMessage"] = "사용자 정보가 정상적으로 수정되었습니다.";

                return RedirectToPage(command);
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;

                return Page();
            }
        }
    }
}