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

using MediatR;
using Microsoft.EntityFrameworkCore;
using CatalogService.Infrastructure;

namespace CatalogService.API.Application.Commands;

/// <summary>
/// EN: Handler for deleting a category.
/// VI: Handler xóa danh mục.
/// </summary>
public class DeleteCategoryCommandHandler : IRequestHandler<DeleteCategoryCommand, bool>
{
    private readonly CatalogContext _context;

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

    public async Task<bool> Handle(DeleteCategoryCommand request, CancellationToken cancellationToken)
    {
        // EN: Retrieve category
        // VI: Lấy danh mục
        var category = await _context.Categories
            .FirstOrDefaultAsync(c => c.Id == request.CategoryId, cancellationToken);

        if (category == null)
        {
            return false;
        }

        // EN: Deactivate category instead of hard delete
        // VI: Vô hiệu hóa danh mục thay vì xóa cứng
        category.Deactivate();

        // EN: Save changes
        // VI: Lưu thay đổi
        await _context.SaveChangesAsync(cancellationToken);

        return true;
    }
}
