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

namespace Admin.Pages.Crypto;

public class CurationModel(IMediator mediator) : PageModel
{
    public int Total { get; private set; } = 0;

    public List<(
        int Num,
        int ID,
        int Index,
        string Symbol,
        string KorName,
        string EngName,
        string? LogoImage,
        bool IsFeatured,
        short DisplayOrder,
        string IsActive
    )> List { get; set; } = [];

    [BindProperty(Name = "request")]
    public List<InputModel> Input { get; private set; } = [];

    public sealed class InputModel
    {
        public int CoinID { get; set; }
        public bool IsFeatured { get; set; } = false;
        public short DisplayOrder { get; set; } = 0;
    }

    public async Task OnGetAsync(CancellationToken ct)
    {
        var result = await mediator.Send(new GetCoinCuration.Query(), ct);

        Total = result.Total;
        List = [..result.List.Select((c, i) => (
            c.Num,
            c.ID,
            i,
            c.Symbol,
            c.KorName,
            c.EngName,
            c.LogoImage,
            c.IsFeatured,
            c.DisplayOrder,
            c.IsActive ? "Y" : "N"
        ))];
    }

    public async Task<IActionResult> OnPostAsync(CancellationToken ct)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                throw new Exception();
            }

            var cmd = new SaveCoinCuration.Command(
                [..Input.Select(x => new SaveCoinCuration.Command.Row(
                    x.CoinID,
                    x.IsFeatured,
                    x.DisplayOrder
                ))]
            );

            await mediator.Send(cmd, ct);

            TempData["SuccessMessage"] = "저장되었습니다.";
        }
        catch (Exception e)
        {
            TempData["ErrorMessages"] = e.Message;
        }

        return RedirectToPage("/Crypto/Curation");
    }
}