import 'package:flutter_test/flutter_test.dart';

import 'package:chanora_flutter/services/prefetch_debouncer.dart';

void main() {
  test('debounces host edits and prefetches latest trimmed host', () async {
    final calls = <String>[];
    final debouncer = PrefetchDebouncer(
      delay: const Duration(milliseconds: 20),
      onPrefetch: (host) async => calls.add(host),
    );

    debouncer.schedule(' first.example.com ');
    debouncer.schedule(' second.example.com ');
    await Future<void>.delayed(const Duration(milliseconds: 35));

    expect(calls, ['second.example.com']);
    debouncer.dispose();
  });

  test('skips empty hosts', () async {
    final calls = <String>[];
    final debouncer = PrefetchDebouncer(
      delay: const Duration(milliseconds: 10),
      onPrefetch: (host) async => calls.add(host),
    );

    debouncer.schedule('   ');
    await Future<void>.delayed(const Duration(milliseconds: 25));

    expect(calls, isEmpty);
    debouncer.dispose();
  });

  test('dispose cancels pending prefetch', () async {
    final calls = <String>[];
    final debouncer = PrefetchDebouncer(
      delay: const Duration(milliseconds: 30),
      onPrefetch: (host) async => calls.add(host),
    );

    debouncer.schedule('example.com');
    debouncer.dispose();
    await Future<void>.delayed(const Duration(milliseconds: 45));

    expect(calls, isEmpty);
  });
}
