using CMSMicroservice.Protobuf.Protos.ClubMembership;
using Google.Protobuf.WellKnownTypes;

namespace FrontOffice.Main.Utilities;

/// <summary>
/// Service for Club Membership operations
/// Connected to CMS gRPC ClubMembershipCQ
/// </summary>
public class ClubMembershipService
{
    private readonly ClubMembershipContract.ClubMembershipContractClient _client;
    private readonly UserAuthInfo _authInfo;

    public ClubMembershipService(
        ClubMembershipContract.ClubMembershipContractClient client,
        UserAuthInfo authInfo)
    {
        _client = client;
        _authInfo = authInfo;
    }

    /// <summary>
    /// Get current user's club membership status
    /// Maps to: ClubMembershipCQ.GetMyClubMembership
    /// </summary>
    public async Task<ClubMembershipDto> GetMyMembershipAsync()
    {
        try
        {
            // UserId = 0 میفرستیم تا CMS از JWT بخونه
            var response = await _client.GetClubMembershipAsync(new GetClubMembershipRequest { UserId = 0 });
            return new ClubMembershipDto
            {
                UserId = response.UserId,
                IsActive = response.IsActive,
                Status = response.Status,
                DaysRemaining = response.DaysRemaining > 0 ? response.DaysRemaining : null
            };
        }
        catch (Exception ex)
        {
            // Log the error for debugging
            Console.WriteLine($"GetMyMembershipAsync error: {ex.Message}");
            
            // Return empty membership if backend is unavailable
            return new ClubMembershipDto
            {
                UserId = 0,
                IsActive = false,
                Status = string.Empty,
                DaysRemaining = null
            };
        }
    }

    /// <summary>
    /// Activate or renew club membership
    /// Maps to: ClubMembershipCQ.ActivateMyClubMembership
    /// </summary>
    public async Task<ClubActivationResponseDto> ActivateMembershipAsync(
        long packageId,
        string? activationCode,
        int durationMonths)
    {
        try
        {
            var userId = await GetCurrentUserIdAsync();
            
            // Check if user is authenticated
            if (userId <= 0)
            {
                return new ClubActivationResponseDto
                {
                    Success = false,
                    Message = "کاربر احراز هویت نشده است. لطفاً ابتدا وارد شوید.",
                    ActivationDate = null,
                    AmountPaid = 0
                };
            }
            
            var request = new ActivateClubMembershipRequest
            {
                UserId = userId,
                PackageId = packageId,
                DurationMonths = durationMonths
            };
            
            if (!string.IsNullOrWhiteSpace(activationCode))
            {
                request.ActivationCode = activationCode;
            }
            
            await _client.ActivateClubMembershipAsync(request);
            // Note: CMS ActivateClubMembership returns Empty, not detailed response
            return new ClubActivationResponseDto
            {
                Success = true,
                Message = "عضویت باشگاه با موفقیت فعال شد.",
                ActivationDate = DateTime.Now,
                AmountPaid = 0 // Not available in CMS response
            };
        }
        catch (Grpc.Core.RpcException ex)
        {
            return new ClubActivationResponseDto
            {
                Success = false,
                Message = ex.Status.Detail ?? "خطا در فعال‌سازی عضویت",
                ActivationDate = null,
                AmountPaid = 0
            };
        }
    }
    
    private Task<long> GetCurrentUserIdAsync()
    {
        return Task.FromResult(_authInfo.UserId);
    }
}
