using CMSMicroservice.Application.Common.Extensions;
using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Application.Common.Models;
using CMSMicroservice.Domain.Enums;
using Mapster;

namespace CMSMicroservice.Application.PackageCQ.Queries.GetCustomerPurchaseHistory;

public class GetCustomerPurchaseHistoryQueryHandler : IRequestHandler<GetCustomerPurchaseHistoryQuery, GetCustomerPurchaseHistoryResponseDto>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;

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

    public async Task<GetCustomerPurchaseHistoryResponseDto> Handle(GetCustomerPurchaseHistoryQuery request, CancellationToken cancellationToken)
    {
        // Resolve UserId from JWT if not specified
        var userId = request.UserId == 0
            ? (long.TryParse(_currentUser.UserId, out var currentUserId) ? currentUserId : 0)
            : request.UserId;

        if (userId == 0)
            throw new UnauthorizedAccessException("User ID not found");

        var query = _context.UserOrders
            .AsNoTracking()
            .Where(x => x.UserId == userId && x.PackageId != null)
            .Include(x => x.Package)
            .Include(x => x.Transaction)
            .AsQueryable();

        // Apply date filters if specified
        if (request.FromDate.HasValue)
            query = query.Where(x => x.Created >= request.FromDate.Value);

        if (request.ToDate.HasValue)
            query = query.Where(x => x.Created <= request.ToDate.Value);

        // Apply PackageType filter if needed (Package entity doesn't have Type enum currently)
        // This would require Package entity to have a PackageType field

        // Order by most recent first
        query = query.OrderByDescending(x => x.Created);

        // Get metadata
        var metaData = await query.GetMetaData(request.PaginationState, cancellationToken);

        // Get paginated results
        var orders = await query
            .PaginatedListAsync(request.PaginationState)
            .ToListAsync(cancellationToken);

        var purchases = orders.Select(order => new PackagePurchaseHistoryDto
        {
            Id = order.Id,
            PackageId = order.PackageId ?? 0,
            PackageName = order.Package?.Title ?? "نامشخص",
            Amount = order.Amount,
            PackageType = 0, // Default, needs Package.PackageType field
            PurchaseDate = order.Created,
            ExpiryDate = order.PaymentDate?.AddDays(365), // Assuming 1 year validity
            Status = order.PaymentStatus,
            StatusMessage = GetStatusMessage(order.PaymentStatus),
            ReferenceCode = order.Transaction?.RefId ?? order.Id.ToString()
        }).ToList();

        return new GetCustomerPurchaseHistoryResponseDto
        {
            MetaData = metaData,
            Purchases = purchases
        };
    }

    private string GetStatusMessage(PaymentStatus status)
    {
        return status switch
        {
            PaymentStatus.Pending => "در انتظار پرداخت",
            PaymentStatus.Success => "فعال",
            PaymentStatus.Reject => "رد شده",
            _ => "نامشخص"
        };
    }
}
