#nullable enable
using Baya.Application.Contracts.Persistence;
using Baya.Application.Models.Common;
using Baya.Application.Models.Reviews;
using Baya.Domain.Entities.Reviews;
using Mediator;

namespace Baya.Application.Features.Reviews.Queries.GetReviewModerationQueue;

internal sealed class GetReviewModerationQueueQueryHandler(IUnitOfWork unitOfWork)
    : IRequestHandler<GetReviewModerationQueueQuery, OperationResult<PagedResult<ModerationQueueItemDto>>>
{
    public async ValueTask<OperationResult<PagedResult<ModerationQueueItemDto>>> Handle(
        GetReviewModerationQueueQuery request, CancellationToken cancellationToken)
    {
        var page = request.Page < 1 ? 1 : request.Page;
        var pageSize = request.PageSize is < 1 or > 100 ? 20 : request.PageSize;

        var status = string.IsNullOrWhiteSpace(request.Status)
            ? ReviewModerationStatus.PendingModeration
            : request.Status;

        if (!ReviewModerationStatus.IsValid(status))
            return OperationResult<PagedResult<ModerationQueueItemDto>>.FailureResult(
                $"Unknown moderation status '{status}'.");

        var result = await unitOfWork.ReviewRepository.GetModerationQueueAsync(status, page, pageSize, cancellationToken);
        return OperationResult<PagedResult<ModerationQueueItemDto>>.SuccessResult(result);
    }
}
