namespace CMSMicroservice.Application.ClubMembershipCQ.Commands.AssignClubFeature;

public class AssignClubFeatureCommandHandler : IRequestHandler<AssignClubFeatureCommand, long>
{
    private readonly IApplicationDbContext _context;

    public AssignClubFeatureCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<long> Handle(AssignClubFeatureCommand request, CancellationToken cancellationToken)
    {
        // بررسی وجود عضویت فعال
        var membership = await _context.ClubMemberships
            .FirstOrDefaultAsync(x => x.UserId == request.UserId && x.IsActive, cancellationToken);

        if (membership == null)
        {
            throw new NotFoundException(nameof(ClubMembership), $"Active membership for UserId: {request.UserId}");
        }

        // بررسی وجود Feature
        var featureExists = await _context.ClubFeatures
            .AnyAsync(x => x.Id == request.FeatureId && x.IsActive, cancellationToken);

        if (!featureExists)
        {
            throw new NotFoundException(nameof(ClubFeature), request.FeatureId);
        }

        // بررسی وجود قبلی
        var existingAssignment = await _context.UserClubFeatures
            .FirstOrDefaultAsync(x => 
                x.UserId == request.UserId && 
                x.ClubFeatureId == request.FeatureId, 
                cancellationToken);

        UserClubFeature entity;

        if (existingAssignment != null)
        {
            // به‌روزرسانی notes
            entity = existingAssignment;
            entity.Notes = request.Notes;

            _context.UserClubFeatures.Update(entity);
        }
        else
        {
            // ایجاد جدید
            entity = new UserClubFeature
            {
                UserId = request.UserId,
                ClubMembershipId = membership.Id,
                ClubFeatureId = request.FeatureId,
                GrantedAt = request.GrantedAt ?? DateTime.Now,
                Notes = request.Notes
            };

            await _context.UserClubFeatures.AddAsync(entity, cancellationToken);
        }

        await _context.SaveChangesAsync(cancellationToken);

        return entity.Id;
    }
}
