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

namespace Indotalent.Features.Setting.Company.Cqrs;

public record DeleteCompanyByIdRequest(string Id);
public record DeleteCompanyByIdCommand(DeleteCompanyByIdRequest Data) : IRequest<bool>;

public class DeleteCompanyByIdHandler : IRequestHandler<DeleteCompanyByIdCommand, bool>
{
    private readonly AppDbContext _context;

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

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

        if (entity == null) return false;

        if (entity.IsDefault) return false;

        var totalCount = await _context.Company.CountAsync(cancellationToken);
        if (totalCount <= 1)
        {
            return false;
        }

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