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

namespace CMSMicroservice.Application.DiscountShopCQ.Queries.GetDiscountProductById;

public class GetDiscountProductByIdQueryHandler : IRequestHandler<GetDiscountProductByIdQuery, DiscountProductDetailDto?>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<DiscountProductDetailDto?> Handle(GetDiscountProductByIdQuery request, CancellationToken cancellationToken)
    {
        var product = await _context.DiscountProducts
            .Where(p => p.Id == request.ProductId)
            .Select(p => new DiscountProductDetailDto
            {
                Id = p.Id,
                Title = p.Title,
                ShortInfomation = p.ShortInfomation,
                FullInformation = p.FullInformation,
                Price = p.Price,
                MaxDiscountPercent = p.MaxDiscountPercent,
                Rate = p.Rate,
                ImagePath = p.ImagePath,
                ThumbnailPath = p.ThumbnailPath,
                SaleCount = p.SaleCount,
                ViewCount = p.ViewCount,
                RemainingCount = p.RemainingCount,
                IsActive = p.IsActive
            })
            .FirstOrDefaultAsync(cancellationToken);

        if (product == null)
            return null;

        // Get categories
        var categories = await _context.DiscountProductCategories
            .Where(pc => pc.ProductId == request.ProductId)
            .Select(pc => new CategoryDto
            {
                Id = pc.Category.Id,
                Name = pc.Category.Name,
                Title = pc.Category.Title
            })
            .ToListAsync(cancellationToken);

        product.Categories = categories;

        // Increment view count
        var productEntity = await _context.DiscountProducts.FindAsync(new object[] { request.ProductId }, cancellationToken);
        if (productEntity != null)
        {
            productEntity.ViewCount++;
            await _context.SaveChangesAsync(cancellationToken);
        }

        return product;
    }
}
