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

namespace Indotalent.Features.Inventory.UnitMeasure.Cqrs;

public record DeleteUnitMeasureByIdRequest(string Id);

public record DeleteUnitMeasureByIdCommand(DeleteUnitMeasureByIdRequest Data) : IRequest<bool>;

public class DeleteUnitMeasureByIdHandler : IRequestHandler<DeleteUnitMeasureByIdCommand, bool>
{
    private readonly AppDbContext _context;

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

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

        if (entity == null) return false;

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