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

namespace Admin.Pages.Forum.Board;

public class ManagerModel(IMediator mediator) : PageModel
{
    public int BoardID { get; set; }
    public List<(int ID, string Name)> BoardList { get; set; } = [];
    public string? QueryString { get; set; }
    public int Total { get; set; }

    public List<(
        int ID,
        int MemberID,
        string MemberEmail,
        string? MemberFullName,
        bool CanEdit,
        bool CanDelete,
        string? UpdatedAt,
        string CreatedAt
    )> Data { get; set; } = [];

    [BindProperty]
    public InputModel Input { get; set; } = new();

    public sealed class InputModel
    {
        public int MemberID { get; set; }
        public bool CanEdit { get; set; }
        public bool CanDelete { get; set; }
    }

    [BindProperty]
    public List<UpdateItemModel> UpdateItems { get; set; } = [];

    public sealed class UpdateItemModel
    {
        public int ID { get; set; }
        public bool CanEdit { get; set; }
        public bool CanDelete { get; set; }
    }

    [BindProperty]
    public int DeleteID { get; set; }

    public async Task OnGetAsync(int id, CancellationToken ct)
    {
        BoardID = id;
        QueryString = Request.QueryString.ToString();

        var boards = await mediator.Send(new SearchBoards.Query(null, null, 1, 100), ct);
        BoardList = [..boards.List.Select(c => (c.ID, c.Name))];

        var result = await mediator.Send(new GetBoardManagers.Query(id), ct);
        Total = result.Total;
        Data = [..result.List.Select(c => (
            c.ID,
            c.MemberID,
            c.MemberEmail,
            c.MemberFullName,
            c.CanEdit,
            c.CanDelete,
            c.UpdatedAt,
            c.CreatedAt
        ))];
    }

    public async Task<IActionResult> OnPostCreateAsync(int id, CancellationToken ct)
    {
        try
        {
            if (!ModelState.IsValid) throw new Exception(ModelState.GetErrorMessages());

            await mediator.Send(new SaveBoardManagers.Command(
                id,
                new SaveBoardManagers.Command.Create(
                    Input.MemberID,
                    Input.CanEdit,
                    Input.CanDelete
                ),
                null,
                null
            ), ct);

            TempData["SuccessMessage"] = "관리자가 추가되었습니다.";
        }
        catch (Exception e)
        {
            TempData["ErrorMessages"] = e.Message;
        }

        return Redirect($"/Forum/Board/Manager/{id}{Request.QueryString}");
    }

    public async Task<IActionResult> OnPostSaveAsync(int id, CancellationToken ct)
    {
        try
        {
            if (!ModelState.IsValid) throw new Exception(ModelState.GetErrorMessages());

            var updates = UpdateItems.Select(x => new SaveBoardManagers.Command.Update(
                x.ID,
                x.CanEdit,
                x.CanDelete
            )).ToList();

            await mediator.Send(new SaveBoardManagers.Command(
                id,
                null,
                updates,
                null
            ), ct);

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

        return Redirect($"/Forum/Board/Manager/{id}{Request.QueryString}");
    }

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

            TempData["SuccessMessage"] = "관리자가 삭제되었습니다.";
        }
        catch (Exception e)
        {
            TempData["ErrorMessages"] = e.Message;
        }

        return Redirect($"/Forum/Board/Manager/{id}{Request.QueryString}");
    }
}