using Application.Abstractions.Identity.Models;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

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

        public async Task<IActionResult> OnGetAsync(string id, CancellationToken ct)
        {
            if (string.IsNullOrEmpty(id))
            {
                TempData["ErrorMessages"] = "유효하지 않은 접근입니다.";
                return RedirectToPage("/Director/User/Index");
            }

            Input = await mediator.Send(new GetUserRoles.Query(id), ct);

            return Page();
        }

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

                var command = new UpdateUserRoles.Command(
                    Input!.User.ID,
                    new UserRolesDto
                    {
                        Roles = [.. (Input.Roles ?? []).Select(r => new UserRolesDto.Checkbox { DisplayValue = r.DisplayValue, IsSelected = r.IsSelected })]
                    }
                );

                await mediator.Send(command, ct);

                TempData["SuccessMessage"] = "권한이 변경되었습니다.";

                return RedirectToPage(new { id = Input.User.ID });
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;

                return Page();
            }
        }
    }
}