#nullable enable
using Baya.Application.Common;
using Baya.Application.Contracts.Common;
using Baya.Application.Contracts.Persistence;
using Baya.Application.Models.Common;
using Baya.Application.Models.Messaging;
using Mediator;

namespace Baya.Application.Features.Messaging.Queries.ListMyTickets;

internal sealed class ListMyTicketsQueryHandler(
    ICurrentUser currentUser,
    IUnitOfWork unitOfWork)
    : IRequestHandler<ListMyTicketsQuery, OperationResult<PagedResult<TicketSummaryDto>>>
{
    public async ValueTask<OperationResult<PagedResult<TicketSummaryDto>>> Handle(ListMyTicketsQuery request, CancellationToken cancellationToken)
    {
        if (currentUser.UserId is not { } userId)
            return OperationResult<PagedResult<TicketSummaryDto>>.UnauthorizedResult("Not authenticated.");

        var (page, pageSize) = Pagination.Normalize(request.Page, request.PageSize);
        var result = await unitOfWork.TicketRepository.ListMyTicketsAsync(userId, request.Status, request.ReferenceCode, request.BookingId, page, pageSize, cancellationToken);
        return OperationResult<PagedResult<TicketSummaryDto>>.SuccessResult(result);
    }
}
