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

namespace CMSMicroservice.Application.TagCQ.Queries.GetProductsByTag;

public class GetProductsByTagQueryHandler : IRequestHandler<GetProductsByTagQuery, List<ProductSimpleDto>>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<List<ProductSimpleDto>> Handle(GetProductsByTagQuery request, CancellationToken cancellationToken)
    {
        // بررسی وجود تگ
        var tagExists = await _context.Tags
            .AnyAsync(t => t.Id == request.TagId, cancellationToken);

        if (!tagExists)
        {
            throw new NotFoundException(nameof(Tag), request.TagId);
        }

        var products = await _context.ProductTags
            .Where(pt => pt.TagId == request.TagId)
            .Include(pt => pt.Product)
            .Select(pt => new ProductSimpleDto
            {
                Id = pt.Product.Id,
                Title = pt.Product.Title,
                Price = pt.Product.Price,
                Inventory = pt.Product.RemainingCount,
                IsActive = true, // Product entity doesn't have IsActive field
                ImagePath = pt.Product.ImagePath
            })
            .ToListAsync(cancellationToken);

        return products;
    }
}
