namespace CMSMicroservice.Application.ClubMembershipCQ.Queries.GetClubMembership;

public class GetClubMembershipQueryHandler : IRequestHandler<GetClubMembershipQuery, ClubMembershipDto?>
{
    private readonly IApplicationDbContext _context;
    private readonly ILogger<GetClubMembershipQueryHandler> _logger;

    public GetClubMembershipQueryHandler(IApplicationDbContext context, ILogger<GetClubMembershipQueryHandler> logger)
    {
        _context = context;
        _logger = logger;
    }

    public async Task<ClubMembershipDto?> Handle(GetClubMembershipQuery request, CancellationToken cancellationToken)
    {
        _logger.LogInformation("GetClubMembership called for UserId: {UserId}", request.UserId);
        
        var membership = await _context.ClubMemberships
            .AsNoTracking()
            .Where(x => x.UserId == request.UserId)
            .Select(x => new ClubMembershipDto
            {
                Id = x.Id,
                UserId = x.UserId,
                IsActive = x.IsActive,
                ActivatedAt = x.ActivatedAt,
                InitialContribution = x.InitialContribution,
                TotalEarned = x.TotalEarned,
                Created = x.Created,
                LastModified = x.LastModified
            })
            .FirstOrDefaultAsync(cancellationToken);

        // اگر کاربر عضویت نداره، یک DTO با وضعیت غیرفعال برگردون
        if (membership == null)
        {
            _logger.LogInformation("No membership found for UserId: {UserId}, returning inactive status", request.UserId);
            return new ClubMembershipDto
            {
                Id = 0,
                UserId = request.UserId,
                IsActive = false,
                ActivatedAt = null,
                InitialContribution = 0,
                TotalEarned = 0,
                Created = DateTimeOffset.UtcNow,
                LastModified = null
            };
        }

        _logger.LogInformation("Membership found for UserId: {UserId}, IsActive: {IsActive}, Id: {Id}", 
            request.UserId, membership.IsActive, membership.Id);

        return membership;
    }
}
