using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Admin.Pages.Config.Basic;

public sealed class ImagesModel(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(Request), ct);

        TempData["SuccessMessage"] = "저장되었습니다.";
        return RedirectToPage();
    }

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

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

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

        public UpdateConfig.Command ToCommand(HttpRequest request)
        {
            bool IsChecked(string key) => request.Form.TryGetValue(key, out var v) && v.Count > 0;

            var delete = new UpdateConfig.Command.ImagesDeleteFlags(
                Favicon: IsChecked("delete_favicon"),
                LogoSquare: IsChecked("delete_logo_square"),
                LogoHorizontal: IsChecked("delete_logo_horizontal"),
                OgDefault: IsChecked("delete_og_default"),
                TwitterImage: IsChecked("delete_twitter_image"),
                AppleTouchIcon: IsChecked("delete_apple_touch_icon"),
                AppIcon192: IsChecked("delete_app_icon_192"),
                AppIcon512: IsChecked("delete_app_icon_512")
            );

            return new(
                Images: Images,
                ImagesDelete: delete
            );
        }
    }
}