using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.DiscountShopCQ.Queries.GetCustomerCart;

public class GetCustomerCartQueryHandler : IRequestHandler<GetCustomerCartQuery, GetCustomerCartQueryResponse>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;

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

    public async Task<GetCustomerCartQueryResponse> Handle(GetCustomerCartQuery request, CancellationToken cancellationToken)
    {
        // Extract UserId from JWT token
        var userId = long.TryParse(_currentUser.UserId, out var id) ? id : 0;
        if (userId == 0)
        {
            throw new UnauthorizedAccessException("User not authenticated");
        }

        // Get all cart items for the current user
        var cartItems = await _context.UserCarts
            .Include(uc => uc.Product)
            .Where(uc => uc.UserId == userId)
            .ToListAsync(cancellationToken);

        var response = new GetCustomerCartQueryResponse
        {
            TotalItemsCount = cartItems.Sum(c => c.Count),
            Message = cartItems.Count > 0 ? "سبد خرید با موفقیت بازیابی شد" : "سبد خرید خالی است"
        };

        foreach (var item in cartItems)
        {
            // Use Product.ThumbnailPath directly
            var thumbnailPath = item.Product?.ThumbnailPath ?? string.Empty;
            var itemPrice = item.Product?.Price ?? 0;
            var itemDiscount = item.Product?.Discount ?? 0;
            var finalPrice = itemPrice * (100 - itemDiscount) / 100;
            var totalItemPrice = finalPrice * item.Count;

            response.Items.Add(new CustomerCartItemModel
            {
                Id = item.Id,
                ProductId = item.ProductId,
                ProductTitle = item.Product?.Title ?? string.Empty,
                ProductShortInformation = item.Product?.ShortInfomation ?? string.Empty, // Typo in DB: ShortInfomation
                ProductPrice = itemPrice,
                ProductDiscount = itemDiscount,
                ProductThumbnailPath = thumbnailPath,
                Count = item.Count,
                TotalItemPrice = totalItemPrice,
                Created = item.Created
            });

            response.TotalPrice += totalItemPrice;
        }

        return response;
    }
}
