using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
using Mapster;

namespace CMSMicroservice.Application.PackageCQ.Queries.GetCustomerPackages;

public class GetCustomerPackagesQueryHandler : IRequestHandler<GetCustomerPackagesQuery, List<GetCustomerPackagesResponseDto>>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<List<GetCustomerPackagesResponseDto>> Handle(GetCustomerPackagesQuery request, CancellationToken cancellationToken)
    {
        var query = _context.Packages
            .AsNoTracking()
            .Where(p => !p.IsDeleted)
            .AsQueryable();

        // فیلتر IsActive
        if (!request.IncludeInactive)
            query = query.Where(p => p.IsActive);

        // مرتب‌سازی بر اساس SortOrder
        query = query.OrderBy(p => p.SortOrder);

        var packages = await query.ToListAsync(cancellationToken);

        return packages.Select(p => new GetCustomerPackagesResponseDto
        {
            Id = p.Id,
            Name = p.Title,
            Title = p.Title,
            Description = p.Description,
            Price = p.Price,
            ImageUrl = p.ImagePath,
            ImagePath = p.ImagePath,
            Currency = "IRR",
            IsAvailable = p.IsActive,
            ValidityDays = 365,
            IsPopular = p.IsBasePackage,
            ShortDescription = p.Description?.Length > 100
                ? p.Description.Substring(0, 100) + "..."
                : p.Description,
            // New fields
            ActivationFee = p.ActivationFee,
            DiscountMultiplier = (double)p.DiscountMultiplier,
            MagicWalletMultiplier = (double)p.MagicWalletMultiplier,
            MagicWalletMaxDeposit = p.MagicWalletMaxDeposit,
            MagicWalletMaxCredit = p.MagicWalletMaxCredit,
            IsBasePackage = p.IsBasePackage,
            SupportsDayaPurchase = p.SupportsDayaPurchase,
            SupportsDirectPurchase = p.SupportsDirectPurchase
        }).ToList();
    }
}
