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

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

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("PostReport.PostNotFound", "게시글을 찾을 수 없습니다."));
        }

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

        var report = new Domain.Entities.Forum.Posts.PostReport
        {
            BoardID = post.BoardID,
            PostID = request.PostID,
            MemberID = request.MemberID,
            Type = request.Type,
            Reason = request.Reason
        };

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

        post.Reports++;

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

        await db.SaveChangesAsync(ct);

        return Result.Success();
    }
}