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

namespace Admin.Pages.Member.Grade
{
    public class IndexModel(IMediator mediator) : PageModel
    {
        public int Total { get; private set; } = 0;

        public List<RowModel> Data { get; private set; } = [];

        public sealed class RowModel
        {
            public int Num { get; set; }
            public int ID { get; set; }
            public required string Name { get; set; }
            public string? Image { get; set; }
            public string? TextColor { get; set; }
            public short Order { get; set; }
            public long TotalDonationCount { get; set; }
            public int TotalDonationAmount { get; set; }
            public int MemberRows { get; set; }
            public char IsActive { get; set; }
            public string? UpdatedAt { get; set; }
            public required string CreatedAt { get; set; }
            public required string EditURL { get; set; }
        }

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

            Total = result.Total;
            Data = [.. result.List.Select(c => new RowModel
            {
                Num = c.Num,
                ID = c.ID,
                Name = c.KorName,
                Image = c.Image,
                TextColor = c.TextColor,
                Order = c.Order,
                TotalDonationCount = c.RequiredAttendance,
                TotalDonationAmount = c.RequiredExp,
                MemberRows = c.MemberRows,
                IsActive = c.IsActive ? 'Y' : 'N',
                UpdatedAt = c.UpdatedAt.GetDateAt() ?? "-",
                CreatedAt = c.CreatedAt.GetDateAt(),
                EditURL = $"/Member/Grade/Edit/{c.ID}"
            })];
        }

        public async Task<IActionResult> OnPostDeleteAsync(int[] ids, CancellationToken ct)
        {
            try
            {
                await mediator.Send(new DeleteMemberGrade.Command(ids), ct);

                TempData["SuccessMessage"] = "회원등급이 삭제되었습니다.";
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
            }

            return RedirectToPage("/Member/Grade/Index");
        }
    }
}