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

using System.Text.Json;
using MediatR;
using CatalogService.API.Application.DTOs;
using CatalogService.Domain.AggregatesModel.ProductAggregate;
using CatalogService.Domain.SeedWork;

namespace CatalogService.API.Application.Queries;

/// <summary>
/// EN: Handler for barcode/SKU product lookup (used by POS scanner).
/// VI: Handler tra cứu sản phẩm theo barcode/SKU (dùng cho máy quét POS).
/// </summary>
public class GetProductByBarcodeQueryHandler : IRequestHandler<GetProductByBarcodeQuery, ProductDto?>
{
    private readonly IProductRepository _repository;
    private readonly ILogger<GetProductByBarcodeQueryHandler> _logger;

    public GetProductByBarcodeQueryHandler(
        IProductRepository repository,
        ILogger<GetProductByBarcodeQueryHandler> logger)
    {
        _repository = repository ?? throw new ArgumentNullException(nameof(repository));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<ProductDto?> Handle(GetProductByBarcodeQuery request, CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "EN: Looking up product by barcode/SKU {Code} in shop {ShopId} / VI: Tra cứu sản phẩm theo barcode/SKU {Code} trong shop {ShopId}",
            request.Barcode, request.ShopId);

        var product = await _repository.GetByBarcodeOrSkuAsync(
            request.ShopId, request.Barcode, cancellationToken);

        if (product == null)
        {
            _logger.LogWarning(
                "EN: Product not found for barcode/SKU {Code} in shop {ShopId} / VI: Không tìm thấy sản phẩm cho barcode/SKU {Code} trong shop {ShopId}",
                request.Barcode, request.ShopId);
            return null;
        }

        // EN: Resolve type name from enumeration
        // VI: Resolve tên loại từ enumeration
        var typeMap = Enumeration.GetAll<ProductType>().ToDictionary(t => t.Id, t => t.Name);

        return new ProductDto
        {
            Id = product.Id,
            ShopId = product.ShopId,
            Name = product.Name,
            Description = product.Description,
            Price = product.Price,
            Type = typeMap.GetValueOrDefault(product.TypeId, "Unknown"),
            Attributes = product.Attributes != null
                ? JsonSerializer.Deserialize<Dictionary<string, object>>(product.Attributes.RootElement.GetRawText())
                : null,
            ImageUrl = product.ImageUrl,
            Sku = product.Sku,
            Barcode = product.Barcode,
            CategoryId = product.CategoryId,
            IsActive = product.IsActive,
            CreatedAt = product.CreatedAt,
            UpdatedAt = product.UpdatedAt
        };
    }
}
