using SharedKernel.Extensions;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.ComponentModel.DataAnnotations;

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

        public List<(
            int Num,
            int ID,
            int Index,
            string Code,
            string Subject,
            short Order,
            char IsActive,
            int FaqItemRows,
            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 Subject { get; set; }

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

            public bool IsActive { get; set; } = false;
        }

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

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

            Total = result.Total;
            List = [..result.List.Select(c => (
                c.Num,
                c.ID,
                c.Index,
                c.Code,
                c.Subject,
                c.Order,
                c.IsActive ? 'Y' : 'N',
                c.FaqItemRows,
                c.UpdatedAt.GetDateAt() ?? "-",
                c.CreatedAt.GetDateAt()
            ))];

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

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

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

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

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

            return RedirectToPage("/Faq/Category");
        }
    }
}