using Application.Abstractions.Messaging;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Admin.Pages.Config
{
    public class RegisterModel(IMediator mediator) : PageModel
    {
        [BindProperty]
        public InputModel Input { get; set; } = new();

        public async Task OnGetAsync(CancellationToken ct)
        {
            var config = await mediator.Send(new GetConfig.Query(), ct);
            if (config is not null)
            {
                Input = InputModel.From(config);
            }
        }

        public async Task<IActionResult> OnPostAsync(CancellationToken ct)
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            await mediator.Send(Input.ToCommand(), ct);

            TempData["SuccessMessage"] = "???????.";
            return RedirectToPage();
        }

        public sealed class InputModel
        {
            public UpdateConfig.Request.AccountConfigDto Account { get; set; } = new();

            public static InputModel From(GetConfig.Response config)
            {
                var req = UpdateConfig.Request.From(config);

                return new()
                {
                    Account = req.Account
                };
            }

            public UpdateConfig.Command ToCommand()
            {
                return new(
                    Account: Account
                );
            }
        }
    }
}