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

using System.Text.Json;
using MediatR;
using Microsoft.EntityFrameworkCore;
using CatalogService.API.Application.DTOs;
using CatalogService.Domain.AggregatesModel.ProductAggregate;
using CatalogService.Domain.SeedWork;
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 typeMap = Enumeration.GetAll<ProductType>().ToDictionary(t => t.Id, t => t.Name);

        var entity = await _context.Products
            .FirstOrDefaultAsync(p => p.Id == request.ProductId, cancellationToken);

        if (entity == null) return null;

        // EN: Resolve category name if categoryId exists
        // VI: Resolve tên danh mục nếu có categoryId
        string? categoryName = null;
        if (entity.CategoryId.HasValue)
        {
            var cat = await _context.Categories.FirstOrDefaultAsync(c => c.Id == entity.CategoryId.Value, cancellationToken);
            categoryName = cat?.Name;
        }

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