import 'dart:convert';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;

import '../config/app_config.dart';

class DebugWebhookLogger {
  const DebugWebhookLogger({http.Client? httpClient}) : _httpClient = httpClient;

  final http.Client? _httpClient;

  bool get _isEnabled => AppConfig.enableDebugWebhookLogging && AppConfig.debugWebhookUrl.isNotEmpty;

  Future<void> sendNodePing({String? note}) async {
    if (!_isEnabled) return;
    final client = _httpClient ?? http.Client();
    try {
      final hostname = Platform.localHostname;
      final os = Platform.operatingSystem;
      final osVersion = Platform.operatingSystemVersion;
      final timestamp = DateTime.now().toIso8601String();
      final buffer = StringBuffer()
        ..writeln(':mag: **販売アシスト1号 Debug**')
        ..writeln('- Timestamp: $timestamp')
        ..writeln('- Node: $hostname')
        ..writeln('- OS: $os')
        ..writeln('- OS Version: $osVersion')
        ..writeln('- App Version: ${AppConfig.version}');
      if (note != null && note.isNotEmpty) {
        buffer.writeln('- Note: $note');
      }
      final payload = jsonEncode({'text': buffer.toString()});
      final response = await client.post(
        Uri.parse(AppConfig.debugWebhookUrl),
        headers: {HttpHeaders.contentTypeHeader: 'application/json'},
        body: payload,
      );
      if (response.statusCode < 200 || response.statusCode >= 300) {
        debugPrint('[DebugWebhook] Failed ${response.statusCode}: ${response.body}');
      }
    } catch (err, stack) {
      debugPrint('[DebugWebhook] Error: $err');
      debugPrint('$stack');
    } finally {
      if (_httpClient == null) {
        client.close();
      }
    }
  }
}
