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