using Indotalent.Infrastructure.Database;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Features.Inventory.ProductGroup.Cqrs;

public record DeleteProductGroupByIdRequest(string Id);

public record DeleteProductGroupByIdCommand(DeleteProductGroupByIdRequest Data) : IRequest<bool>;

public class DeleteProductGroupByIdHandler : IRequestHandler<DeleteProductGroupByIdCommand, bool>
{
    private readonly AppDbContext _context;

    public DeleteProductGroupByIdHandler(AppDbContext context) => _context = context;

    public async Task<bool> Handle(DeleteProductGroupByIdCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.ProductGroup
            .FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);

        if (entity == null) return false;

        _context.ProductGroup.Remove(entity);
        return await _context.SaveChangesAsync(cancellationToken) > 0;
    }
}