namespace CMSMicroservice.Application.WarehouseCQ.Queries.GetAllWarehouses;

public class GetAllWarehousesQueryHandler : IRequestHandler<GetAllWarehousesQuery, GetAllWarehousesResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetAllWarehousesResponseDto> Handle(GetAllWarehousesQuery request, CancellationToken cancellationToken)
    {
        var warehouses = await _context.Warehouses
            .AsNoTracking()
            .OrderBy(w => w.Name)
            .Select(w => new WarehouseItemDto
            {
                Id = w.Id,
                Name = w.Name,
                Code = w.Code,
                Address = w.Address,
                IsDefault = w.IsDefault,
                IsActive = w.IsActive
            })
            .ToListAsync(cancellationToken);

        return new GetAllWarehousesResponseDto
        {
            Warehouses = warehouses,
            TotalCount = warehouses.Count
        };
    }
}
