using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.Pages.Director.Role
{
    public class IndexModel(IMediator mediator) : PageModel
    {
        public int Total { get; set; } = 0;
        public List<GetRoles.Response> List { get; set; } = [];

        [Required]
        [DisplayName("역할(Role)")]
        [MaxLength(100)]
        [BindProperty]
        public string? RoleName { get; set; }

        public async Task OnGetAsync(CancellationToken ct)
        {
            List = await mediator.Send(new GetRoles.Query(), ct);
            Total = List.Count;
        }

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

                var command = new CreateRole.Command(
                    RoleName: RoleName
                );

                await mediator.Send(command, ct);

                TempData["SuccessMessage"] = $"{RoleName} 역할이 추가되었습니다.";

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

                return Page();
            }
        }

        public async Task<IActionResult> OnPostDeleteAsync(string id, CancellationToken ct)
        {
            try
            {
                var role = await mediator.Send(new GetRole.Query(id), ct);
                if (role == null)
                {
                    throw new Exception("존재하지 않는 역할(Role)입니다.");
                }

                await mediator.Send(new DeleteRole.Command(id), ct);

                TempData["SuccessMessage"] = $"{role.Name} 역할이 정상적으로 삭제되었습니다.";
                return RedirectToPage();
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
                return RedirectToPage();
            }
        }
    }
}