DescribeSwitchUseCase.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using RackPeek.Domain.Helpers;
  2. using RackPeek.Domain.Persistence;
  3. using RackPeek.Domain.Resources.SubResources;
  4. namespace RackPeek.Domain.Resources.Switches;
  5. public record SwitchDescription(
  6. string Name,
  7. string? Model,
  8. bool? Managed,
  9. bool? Poe,
  10. int TotalPorts,
  11. double TotalSpeedGb,
  12. string PortSummary,
  13. Dictionary<string, string> Labels
  14. );
  15. public class DescribeSwitchUseCase(IResourceCollection repository) : IUseCase
  16. {
  17. public async Task<SwitchDescription> ExecuteAsync(string name)
  18. {
  19. name = Normalize.HardwareName(name);
  20. ThrowIfInvalid.ResourceName(name);
  21. var switchResource = await repository.GetByNameAsync(name) as Switch;
  22. if (switchResource == null)
  23. throw new NotFoundException($"Switch '{name}' not found.");
  24. // If no ports exist, return defaults
  25. var ports = switchResource.Ports ?? new List<Port>();
  26. // Total ports count
  27. var totalPorts = ports.Sum(p => p.Count ?? 0);
  28. // Total speed (sum of each port speed * count)
  29. var totalSpeedGb = ports.Sum(p => (p.Speed ?? 0) * (p.Count ?? 0));
  30. // Build a port summary string
  31. var portGroups = ports
  32. .GroupBy(p => p.Type ?? "Unknown")
  33. .Select(g =>
  34. {
  35. var count = g.Sum(x => x.Count ?? 0);
  36. var speed = g.Sum(x => (x.Speed ?? 0) * (x.Count ?? 0));
  37. return $"{g.Key}: {count} ports ({speed} Gb total)";
  38. });
  39. var portSummary = string.Join(", ", portGroups);
  40. return new SwitchDescription(
  41. switchResource.Name,
  42. switchResource.Model,
  43. switchResource.Managed,
  44. switchResource.Poe,
  45. totalPorts,
  46. totalSpeedGb,
  47. portSummary,
  48. switchResource.Labels
  49. );
  50. }
  51. }