using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using SharedKernel.Extensions;

namespace Admin.Pages.Forum.Comments.List
{
    public class EditModel(IMediator mediator) : PageModel
    {
        public string? QueryString { get; set; }
        public int CommentID { get; set; }
        public int BoardID { get; set; }
        public string BoardName { get; set; } = "";
        public int PostID { get; set; }
        public string PostSubject { get; set; } = "";
        public string CommentContent { get; set; } = "";
        public string? Name { get; set; }
        public string? SID { get; set; }
        public bool IsReply { get; set; }
        public bool IsSecret { get; set; }
        public bool IsDeleted { get; set; }
        public int Likes { get; set; }
        public int Dislikes { get; set; }
        public int Reports { get; set; }
        public int Replies { get; set; }
        public string? UpdatedAt { get; set; }
        public string CreatedAt { get; set; } = "";

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

            CommentID = result.ID;
            BoardID = result.BoardID;
            BoardName = result.BoardName;
            PostID = result.PostID;
            PostSubject = result.PostSubject;
            CommentContent = result.Content;
            Name = result.Name;
            SID = result.SID;
            IsReply = result.IsReply;
            IsSecret = result.IsSecret;
            IsDeleted = result.IsDeleted;
            Likes = result.Likes;
            Dislikes = result.Dislikes;
            Reports = result.Reports;
            Replies = result.Replies;
            UpdatedAt = result.UpdatedAt.GetDateAt() ?? "-";
            CreatedAt = result.CreatedAt.GetDateAt();
            QueryString = Request.QueryString.ToString();
        }

        public async Task<IActionResult> OnPostDeleteAsync(int id, CancellationToken ct)
        {
            try
            {
                await mediator.Send(new DeleteComment.Command([id]), ct);
                TempData["SuccessMessage"] = "댓글이 삭제되었습니다.";
                return RedirectToPage("/Forum/Comments/List/Index");
            }
            catch (Exception e)
            {
                TempData["ErrorMessages"] = e.Message;
                return Redirect($"/Forum/Comments/List/Edit/{id}{Request.QueryString}");
            }
        }
    }
}
