import 'dart:convert';

import 'package:flutter_test/flutter_test.dart';
import 'package:marianum_mobile/api/marianumcloud/webdav/queries/list_files/cacheable_file.dart';
import 'package:marianum_mobile/api/marianumcloud/webdav/queries/list_files/list_files_response.dart';
import 'package:marianum_mobile/view/pages/files/search/local_cache_search.dart';

CacheableFile _file({
  required String path,
  required String name,
  bool isDirectory = false,
}) => CacheableFile(path: path, isDirectory: isDirectory, name: name);

Map<String, dynamic> _doc(ListFilesResponse listing) => {
  'json': jsonEncode(listing.toJson()),
  'lastupdate': 0,
};

void main() {
  group('searchLocalCaches', () {
    final root = ListFilesResponse({
      _file(path: 'Documents/', name: 'Documents', isDirectory: true),
      _file(path: 'Photos/', name: 'Photos', isDirectory: true),
      _file(path: 'Reports.pdf', name: 'Reports.pdf'),
    });
    final documents = ListFilesResponse({
      _file(path: 'Documents/Tax-Report.pdf', name: 'Tax-Report.pdf'),
      _file(path: 'Documents/Notes.txt', name: 'Notes.txt'),
    });
    final docs = {
      '/MarianumMobile/wd-folder-aaa': _doc(root),
      '/MarianumMobile/wd-folder-bbb': _doc(documents),
      '/MarianumMobile/get-room-ccc': {'json': '{}', 'lastupdate': 0},
    };

    test('matches by name case-insensitively across all caches', () async {
      final hits = await searchLocalCaches('report', docs: docs);
      final paths = hits.map((f) => f.path).toSet();
      expect(paths, {'Reports.pdf', 'Documents/Tax-Report.pdf'});
    });

    test('returns empty list for empty query', () async {
      expect(await searchLocalCaches('   ', docs: docs), isEmpty);
    });

    test('respects pathScope prefix', () async {
      final hits = await searchLocalCaches(
        'report',
        pathScope: ['Documents'],
        docs: docs,
      );
      expect(hits.map((f) => f.path), ['Documents/Tax-Report.pdf']);
    });

    test('ignores non-folder cache documents', () async {
      final hits = await searchLocalCaches('anything', docs: docs);
      // Only documents starting with `wd-folder-` are scanned. The unrelated
      // `get-room-ccc` doc must not crash the helper.
      expect(hits, isEmpty);
    });

    test('deduplicates entries that appear in multiple cached folders',
        () async {
      final shared = _file(
        path: 'Documents/Tax-Report.pdf',
        name: 'Tax-Report.pdf',
      );
      final dedupRoot = ListFilesResponse({shared});
      final dedupDocs = {
        '/MarianumMobile/wd-folder-aaa': _doc(dedupRoot),
        '/MarianumMobile/wd-folder-bbb': _doc(dedupRoot),
      };
      final hits = await searchLocalCaches('tax', docs: dedupDocs);
      expect(hits, hasLength(1));
    });
  });
}
