using Distribution.Infra.UoW; namespace Distribution.Features.Warehouse; public class WarehouseService(IWarehouseRepository repo, IUnitOfWork uow) { private static WarehouseResponse ToResponse(Models.Warehouse w) => new(w.Id, w.Name, w.Location, w.Type, w.VehicleId, w.IsActive, w.CreatedAt); public async Task> GetAllAsync() => (await repo.GetAllAsync()) .Where(w => w.IsActive) .Select(ToResponse) .ToList(); public async Task GetByIdAsync(Guid id) { var warehouse = await repo.GetByIdAsync(id); if (warehouse is null || !warehouse.IsActive) return null; return ToResponse(warehouse); } public async Task CreateAsync(CreateWarehouseRequest request, CancellationToken ct = default) { var warehouse = new Models.Warehouse { Name = request.Name, Location = request.Location, Type = request.Type, VehicleId = request.VehicleId }; await uow.BeginAsync(ct); try { await repo.AddAsync(warehouse); await uow.CommitAsync(ct); } catch { await uow.RollbackAsync(ct); throw; } return ToResponse(warehouse); } public async Task UpdateAsync(Guid id, UpdateWarehouseRequest request, CancellationToken ct = default) { var warehouse = await repo.GetByIdAsync(id); if (warehouse is null || !warehouse.IsActive) return null; warehouse.Name = request.Name; warehouse.Location = request.Location; warehouse.Type = request.Type; warehouse.VehicleId = request.VehicleId; await uow.BeginAsync(ct); try { repo.Update(warehouse); await uow.CommitAsync(ct); } catch { await uow.RollbackAsync(ct); throw; } return ToResponse(warehouse); } public async Task DeleteAsync(Guid id, CancellationToken ct = default) { var warehouse = await repo.GetByIdAsync(id); if (warehouse is null || !warehouse.IsActive) return false; await uow.BeginAsync(ct); try { repo.Remove(warehouse); await uow.CommitAsync(ct); } catch { await uow.RollbackAsync(ct); throw; } return true; } }