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

namespace Admin.Pages.Director.Role
{
    public class PermissionModel(IMediator mediator) : PageModel
    {
        [BindProperty]
        public GetRolePermissions.Response Role { get; set; } = new() { RoleID = string.Empty };

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

            Role = await mediator.Send(new GetRolePermissions.Query(id), ct);

            return Page();
        }

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

                var permissions = new PermissionDto
                {
                    RoleClaims = [.. Role.RoleClaims.Select(g => new PermissionDto.PermissionGroup
                    {
                        Permissions = [.. g.Permissions.Select(p => new PermissionDto.PermissionGroup.Checkbox
                        {
                            DisplayValue = p.DisplayValue,
                            IsSelected = p.IsSelected
                        })]
                    })]
                };

                var command = new UpdateRolePermissions.Command(
                    Role.RoleID,
                    permissions
                );

                await mediator.Send(command, ct);

                TempData["SuccessMessage"] = $"{Role.RoleName} 권한 정보가 수정되었습니다.";

                return RedirectToPage("/Director/Role/Index", new { id = Role.RoleID });
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;

                return Page();
            }
        }
    }
}