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

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

namespace CatalogService.API.Application.Commands;

/// <summary>
/// EN: Handler for deleting a product.
/// VI: Handler xóa sản phẩm.
/// </summary>
public class DeleteProductCommandHandler : IRequestHandler<DeleteProductCommand, bool>
{
    private readonly IProductRepository _productRepository;

    public DeleteProductCommandHandler(IProductRepository productRepository)
    {
        _productRepository = productRepository ?? throw new ArgumentNullException(nameof(productRepository));
    }

    public async Task<bool> Handle(DeleteProductCommand request, CancellationToken cancellationToken)
    {
        // EN: Retrieve product aggregate
        // VI: Lấy product aggregate
        var product = await _productRepository.GetByIdAsync(request.ProductId, cancellationToken);
        
        if (product == null)
        {
            throw new DomainException($"Product with ID {request.ProductId} not found");
        }

        // EN: Deactivate product instead of hard delete
        // VI: Vô hiệu hóa sản phẩm thay vì xóa cứng
        product.Deactivate();

        // EN: Update repository and save
        // VI: Cập nhật repository và lưu
        _productRepository.Update(product);
        await _productRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        return true;
    }
}
