using CMSMicroservice.Application.Common.Exceptions;

namespace CMSMicroservice.Application.WarehouseCQ.Commands.UpdateWarehouse;

public class UpdateWarehouseCommandHandler : IRequestHandler<UpdateWarehouseCommand, UpdateWarehouseResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<UpdateWarehouseResponseDto> Handle(UpdateWarehouseCommand 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);
        }

        // بررسی تکراری نبودن کد جدید
        if (!string.IsNullOrEmpty(request.Code) && request.Code != warehouse.Code)
        {
            var codeExists = await _context.Warehouses
                .AnyAsync(w => w.Code == request.Code && w.Id != request.Id, cancellationToken);
            
            if (codeExists)
            {
                throw new InvalidOperationException($"Warehouse with code '{request.Code}' already exists");
            }
            warehouse.Code = request.Code;
        }

        if (!string.IsNullOrEmpty(request.Name))
        {
            warehouse.Name = request.Name;
        }

        if (request.Address != null)
        {
            warehouse.Address = request.Address;
        }

        if (request.IsActive.HasValue)
        {
            warehouse.IsActive = request.IsActive.Value;
        }

        await _context.SaveChangesAsync(cancellationToken);

        return new UpdateWarehouseResponseDto { Success = true };
    }
}
