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

namespace Application.Features.Api.Forum.CommentReport.Create;

public sealed class Handler(IAppDbContext db) : ICommandHandler<Command, Result>
{
    public async Task<Result> Handle(Command request, CancellationToken ct)
    {
        var comment = await db.Comment.FirstOrDefaultAsync(x => x.ID == request.CommentID, ct);
        if (comment is null)
        {
            return Result.Failure(Error.NotFound("CommentReport.CommentNotFound", "댓글을 찾을 수 없습니다."));
        }

        // 중복 신고 확인
        var exists = await db.CommentReport.AnyAsync(x => x.CommentID == request.CommentID && x.MemberID == request.MemberID, ct);
        if (exists)
        {
            return Result.Failure(Error.Conflict("CommentReport.Duplicate", "이미 신고한 댓글입니다."));
        }

        var report = new Domain.Entities.Forum.Comments.CommentReport
        {
            BoardID = comment.BoardID,
            PostID = comment.PostID,
            CommentID = request.CommentID,
            MemberID = request.MemberID,
            Type = request.Type,
            Reason = request.Reason
        };

        await db.CommentReport.AddAsync(report, ct);

        comment.Reports++;

        // 댓글 작성자의 신고 당한 횟수 증가
        var reportedStats = await db.MemberStats.FirstOrDefaultAsync(x => x.MemberID == comment.MemberID, ct);
        if (reportedStats is not null)
        {
            reportedStats.ReportedCount++;
        }

        await db.SaveChangesAsync(ct);

        return Result.Success();
    }
}