using CMSMicroservice.Protobuf.Protos.Package;
using CMSMicroservice.WebApi.Common.Services;
using CMSMicroservice.Application.PackageCQ.Commands.CreateNewPackage;
using CMSMicroservice.Application.PackageCQ.Commands.UpdatePackage;
using CMSMicroservice.Application.PackageCQ.Commands.DeletePackage;
using CMSMicroservice.Application.PackageCQ.Commands.PurchaseGoldenPackage;
using CMSMicroservice.Application.PackageCQ.Commands.VerifyGoldenPackagePurchase;
using CMSMicroservice.Application.PackageCQ.Commands.InitiateBasePackagePayment;
using CMSMicroservice.Application.PackageCQ.Commands.VerifyBasePackagePayment;
using CMSMicroservice.Application.PackageCQ.Queries.GetPackage;
using CMSMicroservice.Application.PackageCQ.Queries.GetAllPackageByFilter;
using CMSMicroservice.Application.PackageCQ.Queries.GetUserPackageStatus;
using Grpc.Core;
using Google.Protobuf.WellKnownTypes;
using System.Collections.Generic;
using CMSMicroservice.Protobuf.Protos;
namespace CMSMicroservice.WebApi.Services;
public class PackageService : PackageContract.PackageContractBase
{
    private readonly IDispatchRequestToCQRS _dispatchRequestToCQRS;

    public PackageService(IDispatchRequestToCQRS dispatchRequestToCQRS)
    {
        _dispatchRequestToCQRS = dispatchRequestToCQRS;
    }
    public override async Task<CreateNewPackageResponse> CreateNewPackage(CreateNewPackageRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<CreateNewPackageRequest, CreateNewPackageCommand, CreateNewPackageResponse>(request, context);
    }
    public override async Task<Empty> UpdatePackage(UpdatePackageRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<UpdatePackageRequest, UpdatePackageCommand>(request, context);
    }
    public override async Task<Empty> DeletePackage(DeletePackageRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<DeletePackageRequest, DeletePackageCommand>(request, context);
    }
    public override async Task<GetPackageResponse> GetPackage(GetPackageRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<GetPackageRequest, GetPackageQuery, GetPackageResponse>(request, context);
    }
    public override async Task<GetAllPackageByFilterResponse> GetAllPackageByFilter(GetAllPackageByFilterRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<GetAllPackageByFilterRequest, GetAllPackageByFilterQuery, GetAllPackageByFilterResponse>(request, context);
    }
    
    public override async Task<PurchaseGoldenPackageResponse> PurchaseGoldenPackage(PurchaseGoldenPackageRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<PurchaseGoldenPackageRequest, PurchaseGoldenPackageCommand, PurchaseGoldenPackageResponse>(request, context);
    }
    
    public override async Task<VerifyGoldenPackagePurchaseResponse> VerifyGoldenPackagePurchase(VerifyGoldenPackagePurchaseRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<VerifyGoldenPackagePurchaseRequest, VerifyGoldenPackagePurchaseCommand, VerifyGoldenPackagePurchaseResponse>(request, context);
    }
    
    public override async Task<GetUserPackageStatusResponse> GetUserPackageStatus(GetUserPackageStatusRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<GetUserPackageStatusRequest, GetUserPackageStatusQuery, GetUserPackageStatusResponse>(request, context);
    }
    
    // Base Package Payment (56M)
    public override async Task<InitiateBasePackagePaymentResponse> InitiateBasePackagePayment(InitiateBasePackagePaymentRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<InitiateBasePackagePaymentRequest, InitiateBasePackagePaymentCommand, InitiateBasePackagePaymentResponse>(request, context);
    }
    
    public override async Task<VerifyBasePackagePaymentResponse> VerifyBasePackagePayment(VerifyBasePackagePaymentRequest request, ServerCallContext context)
    {
        return await _dispatchRequestToCQRS.Handle<VerifyBasePackagePaymentRequest, VerifyBasePackagePaymentCommand, VerifyBasePackagePaymentResponse>(request, context);
    }
    
    // ============= Customer-specific Method Implementations =============
    
    public override async Task<GetCustomerPackagesResponse> GetCustomerPackages(GetCustomerPackagesRequest request, ServerCallContext context)
    {
        // Mock Customer packages with realistic Persian data
        var packages = new List<CustomerPackageModel>
        {
            new CustomerPackageModel
            {
                Id = 1,
                Name = "پکیج طلایی",
                Title = "پکیج طلایی", // Populate alias field
                Description = "پکیج کامل با امکانات ویژه برای کاربران فعال",
                Price = 5600000,
                Currency = "IRR",
                PackageType = PackageTypeEnum.PackageTypeGolden,
                IsAvailable = true,
                ImageUrl = "/images/packages/golden.jpg",
                ImagePath = "/images/packages/golden.jpg", // Populate alias field
                ValidityDays = 365,
                IsPopular = true,
                ShortDescription = "بهترین انتخاب برای درآمد بیشتر"
            },
            new CustomerPackageModel
            {
                Id = 2,
                Name = "پکیج پریمیوم",
                Title = "پکیج پریمیوم", // Populate alias field
                Description = "پکیج پیشرفته با امکانات حرفه‌ای",
                Price = 3200000,
                Currency = "IRR",
                PackageType = PackageTypeEnum.PackageTypePremium,
                IsAvailable = true,
                ImageUrl = "/images/packages/premium.jpg",
                ImagePath = "/images/packages/premium.jpg", // Populate alias field
                ValidityDays = 180,
                IsPopular = false,
                ShortDescription = "برای کسب و کارهای متوسط"
            },
            new CustomerPackageModel
            {
                Id = 3,
                Name = "پکیج ابتدایی",
                Title = "پکیج ابتدایی", // Populate alias field
                Description = "پکیج مقدماتی برای شروع کار",
                Price = 1500000,
                Currency = "IRR",
                PackageType = PackageTypeEnum.PackageTypeBasic,
                IsAvailable = true,
                ImageUrl = "/images/packages/basic.jpg",
                ImagePath = "/images/packages/basic.jpg", // Populate alias field
                ValidityDays = 90,
                IsPopular = false,
                ShortDescription = "مناسب برای شروع کننده‌ها"
            }
        };
        
        return new GetCustomerPackagesResponse
        {
            Models = { packages }
        };
    }
    
    public override async Task<GetCustomerPackageDetailsResponse> GetCustomerPackageDetails(GetCustomerPackageDetailsRequest request, ServerCallContext context)
    {
        // Mock Customer package details with comprehensive Persian information
        var packageFeatures = new List<PackageFeature>
        {
            new PackageFeature
            {
                Title = "درآمد کمیسیون",
                Description = "دریافت کمیسیون از فروش محصولات",
                Icon = "commission",
                IsHighlighted = true
            },
            new PackageFeature
            {
                Title = "پشتیبانی 24/7",
                Description = "دسترسی به پشتیبانی در تمام ساعات شبانه روز",
                Icon = "support",
                IsHighlighted = false
            },
            new PackageFeature
            {
                Title = "آموزش‌های تخصصی",
                Description = "دسترسی به دوره‌های آموزشی و وبینارها",
                Icon = "education",
                IsHighlighted = true
            }
        };
        
        return new GetCustomerPackageDetailsResponse
        {
            Id = request.PackageId,
            Title = "پکیج طلایی",
            Description = "پکیج کامل با تمام امکانات برای کاربران حرفه‌ای",
            Price = 5600000,
            ImagePath = "/images/packages/golden-detail.jpg",
            Features = { packageFeatures },
            Requirements = new PurchaseRequirements
            {
                RequiresMembership = false,
                MinimumWalletBalance = 560000,
                Restrictions = { "باید حداقل 18 سال سن داشته باشید", "تایید هویت الزامی است" }
            }
        };
    }
    
    public override async Task<CustomerPurchasePackageResponse> CustomerPurchasePackage(CustomerPurchasePackageRequest request, ServerCallContext context)
    {
        // Mock Customer package purchase with realistic Persian response
        var orderId = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
        var authority = "A" + orderId.ToString("D19");
        
        return new CustomerPurchasePackageResponse
        {
            Success = true,
            Message = "درخواست خرید پکیج با موفقیت ثبت شد",
            OrderId = orderId,
            PaymentGatewayUrl = $"https://payment.gateway.com/payment?authority={authority}&amount={GetPackagePrice(request.PackageId)}",
            Authority = authority
        };
    }
    
    public override async Task<CustomerVerifyPackagePurchaseResponse> CustomerVerifyPackagePurchase(CustomerVerifyPackagePurchaseRequest request, ServerCallContext context)
    {
        // Mock Customer purchase verification with realistic Persian data
        var transactionId = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
        var referenceCode = "REF" + transactionId.ToString();
        
        var isSuccessful = request.Status == "OK";
        
        return new CustomerVerifyPackagePurchaseResponse
        {
            Success = isSuccessful,
            Message = isSuccessful ? "خرید پکیج با موفقیت تایید شد" : "خرید پکیج ناموفق بود",
            TransactionId = transactionId,
            ReferenceCode = referenceCode,
            PurchaseInfo = isSuccessful ? new PackagePurchaseInfo
            {
                PackageId = 1,
                PackageName = "پکیج طلایی",
                AmountPaid = 5600000,
                PurchaseDate = Timestamp.FromDateTime(DateTime.UtcNow),
                ExpiryDate = Timestamp.FromDateTime(DateTime.UtcNow.AddDays(365))
            } : null
        };
    }
    
    public override async Task<GetCustomerPurchaseHistoryResponse> GetCustomerPurchaseHistory(GetCustomerPurchaseHistoryRequest request, ServerCallContext context)
    {
        // Mock Customer purchase history with realistic Persian data
        var purchases = new List<PackagePurchaseHistory>
        {
            new PackagePurchaseHistory
            {
                Id = 1,
                PackageId = 1,
                PackageName = "پکیج طلایی",
                Amount = 5600000,
                PackageType = PackageTypeEnum.PackageTypeGolden,
                PurchaseDate = Timestamp.FromDateTime(DateTime.UtcNow.AddDays(-30)),
                ExpiryDate = Timestamp.FromDateTime(DateTime.UtcNow.AddDays(335)),
                Status = PaymentStatusEnum.PaymentStatusSuccess,
                StatusMessage = "فعال",
                ReferenceCode = "REF123456789"
            },
            new PackagePurchaseHistory
            {
                Id = 2,
                PackageId = 2,
                PackageName = "پکیج پریمیوم",
                Amount = 3200000,
                PackageType = PackageTypeEnum.PackageTypePremium,
                PurchaseDate = Timestamp.FromDateTime(DateTime.UtcNow.AddDays(-180)),
                ExpiryDate = Timestamp.FromDateTime(DateTime.UtcNow.AddDays(-150)),
                Status = PaymentStatusEnum.PaymentStatusSuccess,
                StatusMessage = "منقضی شده",
                ReferenceCode = "REF987654321"
            }
        };
        
        return new GetCustomerPurchaseHistoryResponse
        {
            MetaData = new MetaData
            {
                CurrentPage = request.PaginationState?.PageNumber ?? 1,
                TotalPage = 1,
                PageSize = request.PaginationState?.PageSize ?? 10,
                TotalCount = purchases.Count,
                HasPrevious = false,
                HasNext = false
            },
            Purchases = { purchases }
        };
    }
    
    private long GetPackagePrice(long packageId)
    {
        return packageId switch
        {
            1 => 5600000,  // Golden
            2 => 3200000,  // Premium  
            3 => 1500000,  // Basic
            _ => 1000000   // Default
        };
    }
}
