using CMSMicroservice.Application.Common.Exceptions;

namespace CMSMicroservice.Application.WarehouseCQ.Commands.DeleteWarehouse;

public class DeleteWarehouseCommandHandler : IRequestHandler<DeleteWarehouseCommand, DeleteWarehouseResponseDto>
{
    private readonly IApplicationDbContext _context;

    public DeleteWarehouseCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<DeleteWarehouseResponseDto> Handle(DeleteWarehouseCommand request, CancellationToken cancellationToken)
    {
        var warehouse = await _context.Warehouses
            .FirstOrDefaultAsync(w => w.Id == request.Id, cancellationToken);

        if (warehouse == null)
        {
            throw new NotFoundException(nameof(Domain.Entities.Warehouse), request.Id);
        }

        // بررسی اینکه انبار دارای موجودی نباشد
        var hasInventory = await _context.InventoryItems
            .AnyAsync(i => i.WarehouseId == request.Id, cancellationToken);

        if (hasInventory)
        {
            throw new InvalidOperationException("Cannot delete warehouse with existing inventory items");
        }

        _context.Warehouses.Remove(warehouse);
        await _context.SaveChangesAsync(cancellationToken);

        return new DeleteWarehouseResponseDto { Success = true };
    }
}
