import 'dart:developer';

class DatabasePerformanceMonitor {
  static final Map<String, List<int>> _queryTimes = {};

  static Future<T> monitorQuery<T>(
    String queryName,
    Future<T> Function() query,
  ) async {
    final stopwatch = Stopwatch()..start();

    try {
      final result = await query();
      stopwatch.stop();

      _recordQueryTime(queryName, stopwatch.elapsedMilliseconds);

      return result;
    } catch (e) {
      stopwatch.stop();
      log('Query "$queryName" failed after ${stopwatch.elapsedMilliseconds}ms: $e');
      rethrow;
    }
  }

  static void _recordQueryTime(String queryName, int milliseconds) {
    if (!_queryTimes.containsKey(queryName)) {
      _queryTimes[queryName] = [];
    }

    _queryTimes[queryName]!.add(milliseconds);

    // Keep only last 100 entries
    if (_queryTimes[queryName]!.length > 100) {
      _queryTimes[queryName]!.removeAt(0);
    }

    // Log slow queries
    if (milliseconds > 1000) {
      log('Slow query detected: "$queryName" took ${milliseconds}ms');
    }
  }

  static Map<String, dynamic> getPerformanceStats() {
    final stats = <String, dynamic>{};

    _queryTimes.forEach((queryName, times) {
      if (times.isNotEmpty) {
        final avgTime = times.reduce((a, b) => a + b) / times.length;
        final maxTime = times.reduce((a, b) => a > b ? a : b);
        final minTime = times.reduce((a, b) => a < b ? a : b);

        stats[queryName] = {
          'average_ms': avgTime.round(),
          'max_ms': maxTime,
          'min_ms': minTime,
          'total_queries': times.length,
        };
      }
    });

    return stats;
  }
}
