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

using MediatR;
using CatalogService.Domain.AggregatesModel.ProductAggregate;
using CatalogService.Infrastructure;

namespace CatalogService.API.Application.Commands;

/// <summary>
/// EN: Handler for creating a new category.
/// VI: Handler để tạo danh mục mới.
/// </summary>
public class CreateCategoryCommandHandler : IRequestHandler<CreateCategoryCommand, Guid>
{
    private readonly CatalogContext _context;

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

    public async Task<Guid> Handle(CreateCategoryCommand request, CancellationToken cancellationToken)
    {
        // EN: Create category entity
        // VI: Tạo category entity
        var category = new Category(
            shopId: request.ShopId,
            name: request.Name,
            description: request.Description,
            parentId: request.ParentId,
            displayOrder: request.DisplayOrder);

        // EN: Update image if provided
        // VI: Cập nhật hình ảnh nếu được cung cấp
        if (request.ImageUrl != null)
        {
            category.UpdateImage(request.ImageUrl);
        }

        // EN: Add to context and save
        // VI: Thêm vào context và lưu
        _context.Categories.Add(category);
        await _context.SaveChangesAsync(cancellationToken);

        return category.Id;
    }
}
