namespace CMSMicroservice.Application.ClubMembershipCQ.Commands.DeactivateClubMembership;

public class DeactivateClubMembershipCommandHandler : IRequestHandler<DeactivateClubMembershipCommand, Unit>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;

    public DeactivateClubMembershipCommandHandler(
        IApplicationDbContext context,
        ICurrentUserService currentUser)
    {
        _context = context;
        _currentUser = currentUser;
    }

    public async Task<Unit> Handle(DeactivateClubMembershipCommand request, CancellationToken cancellationToken)
    {
        var membership = await _context.ClubMemberships
            .FirstOrDefaultAsync(x => x.UserId == request.UserId, cancellationToken);

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

        // اگر از قبل غیرفعال است، هیچ کاری نکن
        if (!membership.IsActive)
        {
            return Unit.Value;
        }

        membership.IsActive = false;

        _context.ClubMemberships.Update(membership);
        await _context.SaveChangesAsync(cancellationToken);

        // ثبت تاریخچه
        var history = new ClubMembershipHistory
        {
            ClubMembershipId = membership.Id,
            UserId = membership.UserId,
            OldIsActive = true,
            NewIsActive = false,
            Action = ClubMembershipAction.Deactivated,
            Reason = request.Reason ?? "Manual deactivation",
            PerformedBy = _currentUser.GetPerformedBy()
        };

        await _context.ClubMembershipHistories.AddAsync(history, cancellationToken);
        await _context.SaveChangesAsync(cancellationToken);

        return Unit.Value;
    }
}
