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

namespace Admin.Pages.Crypto.Board
{
    public class IndexModel(IMediator mediator) : PageModel
    {
        public int CoinID { get; private set; }
        public string CoinSymbol { get; private set; } = string.Empty;
        public string CoinName { get; private set; } = string.Empty;

        public List<(int ID, string Code, string Name, string GroupName, char IsActive)> Linked { get; set; } = [];
        public List<(int ID, string Code, string Name, string GroupName, char IsActive)> Unlinked { get; set; } = [];

        public async Task<IActionResult> OnGetAsync(int coinID, CancellationToken ct)
        {
            try
            {
                var result = await mediator.Send(new GetCoinBoards.Query(coinID), ct);

                CoinID = coinID;
                CoinSymbol = result.CoinSymbol;
                CoinName = result.CoinKorName;

                Linked = [..result.Linked.Select(b => (b.ID, b.Code, b.Name, b.GroupName, b.IsActive ? 'Y' : 'N'))];
                Unlinked = [..result.Unlinked.Select(b => (b.ID, b.Code, b.Name, b.GroupName, b.IsActive ? 'Y' : 'N'))];

                return Page();
            }
            catch (KeyNotFoundException)
            {
                return NotFound();
            }
        }

        public async Task<IActionResult> OnPostLinkAsync(int coinID, int boardID, CancellationToken ct)
        {
            try
            {
                await mediator.Send(new LinkCoinBoard.Command(coinID, boardID), ct);

                TempData["SuccessMessage"] = "게시판이 연결되었습니다.";
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
            }

            return RedirectToPage("/Crypto/Board/Index", new { coinID });
        }

        public async Task<IActionResult> OnPostUnlinkAsync(int coinID, int boardID, CancellationToken ct)
        {
            try
            {
                await mediator.Send(new UnlinkCoinBoard.Command(boardID), ct);

                TempData["SuccessMessage"] = "게시판 연결이 해제되었습니다.";
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
            }

            return RedirectToPage("/Crypto/Board/Index", new { coinID });
        }
    }
}