using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Protobuf.Protos.ClubMembership;
using CMSMicroservice.WebApi.Common.Services;
using CMSMicroservice.Application.ClubMembershipCQ.Commands.ActivateClubMembership;
using CMSMicroservice.Application.ClubMembershipCQ.Commands.DeactivateClubMembership;
using CMSMicroservice.Application.ClubMembershipCQ.Commands.AssignClubFeature;
using CMSMicroservice.Application.ClubMembershipCQ.Commands.AcceptClubMembershipContract;
using CMSMicroservice.Application.ClubMembershipCQ.Queries.GetClubMembership;
using CMSMicroservice.Application.ClubMembershipCQ.Queries.GetAllClubMemberships;
using CMSMicroservice.Application.ClubMembershipCQ.Queries.GetClubMembershipHistory;
using CMSMicroservice.Application.ClubMembershipCQ.Queries.GetClubStatistics;
using CMSMicroservice.Application.ClubFeatureCQ.Queries.GetUserClubFeatures;
using CMSMicroservice.Application.ClubFeatureCQ.Commands.ToggleUserClubFeature;
using Microsoft.Extensions.Logging;

namespace CMSMicroservice.WebApi.Services;

public class ClubMembershipService : ClubMembershipContract.ClubMembershipContractBase
{
    private readonly IDispatchRequestToCQRS _dispatchRequestToCQRS;
    private readonly ICurrentUserService _currentUserService;
    private readonly ILogger<ClubMembershipService> _logger;

    public ClubMembershipService(
        IDispatchRequestToCQRS dispatchRequestToCQRS,
        ICurrentUserService currentUserService,
        ILogger<ClubMembershipService> logger)
    {
        _dispatchRequestToCQRS = dispatchRequestToCQRS;
        _currentUserService = currentUserService;
        _logger = logger;
    }

    public override async Task<Empty> ActivateClubMembership(ActivateClubMembershipRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<ActivateClubMembershipRequest, ActivateClubMembershipCommand>(request, context);
    }

    public override async Task<Empty> DeactivateClubMembership(DeactivateClubMembershipRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<DeactivateClubMembershipRequest, DeactivateClubMembershipCommand>(request, context);
    }

    public override async Task<Empty> AssignFeatureToMembership(AssignFeatureToMembershipRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<AssignFeatureToMembershipRequest, AssignClubFeatureCommand>(request, context);
    }

    public override async Task<GetClubMembershipResponse> GetClubMembership(GetClubMembershipRequest request, ServerCallContext context)
    {
        // اگر UserId در request نیست یا صفر است، از JWT بخوان
        if (request.UserId <= 0)
        {
            if (long.TryParse(_currentUserService.UserId, out var tokenUserId) && tokenUserId > 0)
            {
                _logger.LogInformation("GetClubMembership: Reading UserId from JWT token: {UserId}", tokenUserId);
                request = new GetClubMembershipRequest { UserId = tokenUserId };
            }
            else
            {
                _logger.LogWarning("GetClubMembership: No valid UserId in request or JWT token");
                throw new RpcException(new Status(StatusCode.Unauthenticated, "کاربر احراز هویت نشده است"));
            }
        }
        else
        {
            _logger.LogInformation("GetClubMembership: Using UserId from request: {UserId}", request.UserId);
        }
        
        return await _dispatchRequestToCQRS.Handle<GetClubMembershipRequest, GetClubMembershipQuery, GetClubMembershipResponse>(request, context);
    }

    public override async Task<GetAllClubMembershipsResponse> GetAllClubMemberships(GetAllClubMembershipsRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<GetAllClubMembershipsRequest, GetAllClubMembershipsQuery, GetAllClubMembershipsResponse>(request, context);
    }

    public override async Task<GetClubMembershipHistoryResponse> GetClubMembershipHistory(GetClubMembershipHistoryRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<GetClubMembershipHistoryRequest, GetClubMembershipHistoryQuery, GetClubMembershipHistoryResponse>(request, context);
    }

    public override async Task<GetClubStatisticsResponse> GetClubStatistics(GetClubStatisticsRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<GetClubStatisticsRequest, GetClubStatisticsQuery, GetClubStatisticsResponse>(request, context);
    }

    public override async Task<GetUserClubFeaturesResponse> GetUserClubFeatures(GetUserClubFeaturesRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<GetUserClubFeaturesRequest, GetUserClubFeaturesQuery, GetUserClubFeaturesResponse>(request, context);
    }

    public override async Task<Protobuf.Protos.ClubMembership.ToggleUserClubFeatureResponse> ToggleUserClubFeature(ToggleUserClubFeatureRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<ToggleUserClubFeatureRequest, ToggleUserClubFeatureCommand, Protobuf.Protos.ClubMembership.ToggleUserClubFeatureResponse>(request, context);
    }

    public override async Task<AcceptClubMembershipContractResponse> AcceptClubMembershipContract(AcceptClubMembershipContractRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<AcceptClubMembershipContractRequest, AcceptClubMembershipContractCommand, AcceptClubMembershipContractResponse>(request, context);
    }
}
