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

namespace Indotalent.Features.Thirdparty.Vendor.Cqrs;

public record DeleteVendorByIdRequest(string Id);

public record DeleteVendorByIdCommand(DeleteVendorByIdRequest Data) : IRequest<bool>;

public class DeleteVendorByIdHandler : IRequestHandler<DeleteVendorByIdCommand, bool>
{
    private readonly AppDbContext _context;

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

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

        if (entity == null) return false;

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