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

namespace Indotalent.Features.Multitenant.Tenant.Cqrs;

public record DeleteTenantByIdRequest(string Id);

public record DeleteTenantByIdCommand(DeleteTenantByIdRequest Data) : IRequest<bool>;

public class DeleteTenantByIdHandler : IRequestHandler<DeleteTenantByIdCommand, bool>
{
    private readonly AppDbContext _context;

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

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

        if (entity == null) return false;

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