// EN: Handler for GetProductByIdQuery.
// VI: Handler cho GetProductByIdQuery.

using System.Text.Json;
using MediatR;
using Microsoft.EntityFrameworkCore;
using CatalogService.API.Application.DTOs;
using CatalogService.Infrastructure;

namespace CatalogService.API.Application.Queries;

/// <summary>
/// EN: Handler for querying a single product by ID.
/// VI: Handler query một sản phẩm theo ID.
/// </summary>
public class GetProductByIdQueryHandler : IRequestHandler<GetProductByIdQuery, ProductDto?>
{
    private readonly CatalogContext _context;

    public GetProductByIdQueryHandler(CatalogContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public async Task<ProductDto?> Handle(GetProductByIdQuery request, CancellationToken cancellationToken)
    {
        var product = await _context.Products
            .Where(p => p.Id == request.ProductId)
            .Select(p => new ProductDto
            {
                Id = p.Id,
                ShopId = p.ShopId,
                Name = p.Name,
                Description = p.Description,
                Price = p.Price,
                Type = p.Type.Name,
                Attributes = p.Attributes != null 
                    ? JsonSerializer.Deserialize<Dictionary<string, object>>(p.Attributes.RootElement.GetRawText())
                    : null,
                ImageUrl = p.ImageUrl,
                Sku = p.Sku,
                IsActive = p.IsActive,
                CreatedAt = p.CreatedAt,
                UpdatedAt = p.UpdatedAt
            })
            .FirstOrDefaultAsync(cancellationToken);

        return product;
    }
}
