deleteDevice method

Future<void> deleteDevice(
  1. String deviceKey
)

Permanently deletes a device from the tailnet.

Implementation

Future<void> deleteDevice(String deviceKey) async {
  final device = await Database.instance.devices.id(deviceKey).get();
  if (device == null) {
    _logger.log('Cannot delete device: No device found for key $deviceKey');
    return;
  }

  final deviceIP = device.ip;
  if (deviceIP == null) {
    _logger.log(
      'Cannot delete device: No device IP found for key $deviceKey',
    );
    return;
  }

  final apiKey = adminApiKey;
  final tailnet = tailnetId;

  if (apiKey == null || tailnet == null) {
    _logger.log('Cannot delete device: Missing admin credentials');
    return;
  }

  try {
    final deviceId = await _getDeviceTailnetId(
      ip: deviceIP,
      apiKey: apiKey,
      tailnetId: tailnet,
    );
    if (deviceId == null) {
      _logger.log('Cannot delete device: No device found for IP $deviceIP');
      return;
    }

    final url = Uri.parse('$_baseUrl/device/$deviceId');
    final basicAuth = 'Basic ${base64Encode(utf8.encode('$apiKey:'))}';

    final response = await http.delete(
      url,
      headers: {'Authorization': basicAuth},
    );

    if (response.statusCode == 200) {
      _logger.log('Successfully deleted device $deviceId ($deviceIP)');
    } else {
      _logger.log(
        'Failed to delete device $deviceId: ${response.statusCode} - ${response.body}',
      );
    }
  } catch (e) {
    _logger.log('Error deleting device $deviceIP: $e');
  }
}