namespace CMSMicroservice.Application.WarehouseCQ.Queries.SearchWarehouses;

public class SearchWarehousesQueryHandler : IRequestHandler<SearchWarehousesQuery, SearchWarehousesResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<SearchWarehousesResponseDto> Handle(SearchWarehousesQuery request, CancellationToken cancellationToken)
    {
        var query = _context.Warehouses.AsNoTracking();

        // فیلتر بر اساس جستجو
        if (!string.IsNullOrEmpty(request.SearchTerm))
        {
            query = query.Where(w =>
                w.Name.Contains(request.SearchTerm) ||
                w.Code.Contains(request.SearchTerm) ||
                (w.Address != null && w.Address.Contains(request.SearchTerm)));
        }

        // فیلتر بر اساس فعال بودن
        if (request.IsActive.HasValue)
        {
            query = query.Where(w => w.IsActive == request.IsActive.Value);
        }

        var totalCount = await query.CountAsync(cancellationToken);

        var warehouses = await query
            .OrderBy(w => w.Name)
            .Skip(request.Skip)
            .Take(request.Take)
            .Select(w => new WarehouseSearchItemDto
            {
                Id = w.Id,
                Name = w.Name,
                Code = w.Code,
                Address = w.Address,
                IsDefault = w.IsDefault,
                IsActive = w.IsActive
            })
            .ToListAsync(cancellationToken);

        return new SearchWarehousesResponseDto
        {
            Warehouses = warehouses,
            TotalCount = totalCount
        };
    }
}
