using Application.Abstractions.Messaging;
using Application.Abstractions.Data;
using Microsoft.EntityFrameworkCore;
using SharedKernel.Results;

namespace Application.Features.Api.Forum.PostBookmark.Toggle;

public sealed class Handler(IAppDbContext db) : ICommandHandler<Command, Result>
{
    public async Task<Result> Handle(Command request, CancellationToken ct)
    {
        var post = await db.Post.FirstOrDefaultAsync(x => x.ID == request.PostID, ct);
        if (post is null)
        {
            return Result.Failure(Error.NotFound("PostBookmark.PostNotFound", "게시글을 찾을 수 없습니다."));
        }

        var existing = await db.PostBookmark.FirstOrDefaultAsync(x => x.PostID == request.PostID && x.MemberID == request.MemberID, ct);

        if (existing is not null)
        {
            db.PostBookmark.Remove(existing);
            post.Bookmarks--;
        }
        else
        {
            var bookmark = new Domain.Entities.Forum.Posts.PostBookmark
            {
                BoardID = post.BoardID,
                PostID = request.PostID,
                MemberID = request.MemberID,
                IpAddress = request.IpAddress,
                UserAgent = request.UserAgent
            };

            db.PostBookmark.Add(bookmark);
            post.Bookmarks++;
        }

        // MemberStats 북마크 수 갱신
        var memberStats = await db.MemberStats.FirstOrDefaultAsync(x => x.MemberID == request.MemberID, ct);
        if (memberStats is not null)
        {
            if (existing is not null)
            {
                memberStats.BookmarkGivenCount--;
            }
            else
            {
                memberStats.BookmarkGivenCount++;
            }
        }

        await db.SaveChangesAsync(ct);

        return Result.Success();
    }
}