using CMSMicroservice.Domain.Entities;

namespace CMSMicroservice.Application.WarehouseCQ.Commands.CreateWarehouse;

public class CreateWarehouseCommandHandler : IRequestHandler<CreateWarehouseCommand, CreateWarehouseResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<CreateWarehouseResponseDto> Handle(CreateWarehouseCommand request, CancellationToken cancellationToken)
    {
        // بررسی تکراری نبودن کد
        var codeExists = await _context.Warehouses
            .AnyAsync(w => w.Code == request.Code, cancellationToken);
        
        if (codeExists)
        {
            throw new InvalidOperationException($"Warehouse with code '{request.Code}' already exists");
        }

        var entity = new Warehouse
        {
            Name = request.Name,
            Code = request.Code,
            Address = request.Address,
            IsActive = request.IsActive,
            IsDefault = request.IsDefault
        };

        await _context.Warehouses.AddAsync(entity, cancellationToken);
        await _context.SaveChangesAsync(cancellationToken);

        return new CreateWarehouseResponseDto { Id = entity.Id };
    }
}
