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

namespace Admin.Pages.Forum.Board
{
    public class GroupModel(IMediator mediator) : PageModel
    {
        public int Total { get; private set; } = 0;

        public List<(
            int Num,
            int ID,
            int Index,
            string Code,
            string Name,
            short Order,
            short Boards,
            int Posts,
            int Comments,
            string? UpdatedAt,
            string CreatedAt
        )> List { get; set; } = [];

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

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

        public sealed class InputModel
        {
            public int? ID { get; set; }

            [Required]
            [StringLength(30)]
            public required string Code { get; set; }

            [Required]
            [StringLength(255)]
            public required string Name { get; set; }

            [Range(-999, 999)]
            public short Order { get; set; }
        }

        public async Task OnGetAsync(CancellationToken ct)
        {
            if (!ModelState.IsValid)
            {
                return;
            }

            var result = await mediator.Send(new GetBoardGroups.Query(), ct);

            Total = result.Total;
            List = [..result.List.Select(c => (
                c.Num,
                c.ID,
                c.Index,
                c.Code,
                c.Name,
                c.Order,
                c.Boards,
                c.Posts,
                c.Comments,
                c.UpdatedAt.GetDateAt() ?? "-",
                c.CreatedAt.GetDateAt()
            ))];

            Data = [..result.List.Select(x => new InputModel
            {
                ID = x.ID,
                Code = x.Code,
                Name = x.Name,
                Order = x.Order
            })];
        }

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

                var cmd = new SaveBoardGroups.Command(
                    [..Input.Select(x => new SaveBoardGroups.Command.Row(
                        x.ID,
                        x.Code,
                        x.Name,
                        x.Order
                    ))]
                );

                var response = await mediator.Send(cmd, ct);

                TempData["SuccessMessage"] = $"저장 완료 (추가: {response.Inserted}, 수정: {response.Updated}, 삭제: {response.Deleted})";
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
            }

            return RedirectToPage("/Forum/Board/Group");
        }
    }
}