import 'dart:convert';

import 'package:localstore/localstore.dart';

import '../../../../api/marianumcloud/webdav/queries/list_files/cacheable_file.dart';
import '../../../../api/marianumcloud/webdav/queries/list_files/list_files_response.dart';
import '../../../../api/request_cache.dart';

/// Document key prefix used by `ListFilesCache._documentId`.
const String _folderCachePrefix = 'wd-folder-';

/// Scans every cached folder listing in Localstore and returns files/folders
/// whose name contains [query] (case-insensitive).
///
/// [pathScope] restricts results to entries whose WebDAV path starts with
/// the given folder. Pass an empty list (or null) to search globally.
///
/// [docs] is an injection seam for tests — production callers leave it null
/// so the helper reads from the real Localstore.
Future<List<CacheableFile>> searchLocalCaches(
  String query, {
  List<String>? pathScope,
  Map<String, dynamic>? docs,
}) async {
  final trimmed = query.trim();
  if (trimmed.isEmpty) return const [];
  final needle = trimmed.toLowerCase();
  final scopePrefix = pathScope == null || pathScope.isEmpty
      ? ''
      : '${pathScope.join('/')}/';

  final raw =
      docs ??
      await Localstore.instance.collection(RequestCache.collection).get();
  if (raw == null || raw.isEmpty) return const [];

  final results = <String, CacheableFile>{};
  for (final entry in raw.entries) {
    final docKey = entry.key.split('/').last;
    if (!docKey.startsWith(_folderCachePrefix)) continue;

    final value = entry.value;
    if (value is! Map) continue;
    final json = value['json'];
    if (json is! String) continue;

    final ListFilesResponse listing;
    try {
      listing = ListFilesResponse.fromJson(
        jsonDecode(json) as Map<String, dynamic>,
      );
    } on Object {
      continue;
    }

    for (final file in listing.files) {
      if (!file.name.toLowerCase().contains(needle)) continue;
      if (scopePrefix.isNotEmpty && !file.path.startsWith(scopePrefix)) {
        continue;
      }
      results[file.path] ??= file;
    }
  }
  return results.values.toList();
}
