using Application.Abstractions.Messaging;
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();
            }
        }
    }
}