import 'package:nextcloud/nextcloud.dart';

import '../../../../../api/demo/data/demo_files.dart';
import '../../../../../api/demo/demo_mode.dart';
import '../../../../../api/marianumcloud/webdav/queries/list_files/list_files_cache.dart';
import '../../../../../api/marianumcloud/webdav/queries/list_files/list_files_response.dart';
import '../../../../../api/marianumcloud/webdav/webdav_api.dart';
import '../../../../../api/request_cache.dart';

class FilesDataProvider {
  /// Lists files at [path]. Cached payload is delivered via [onCacheData] the
  /// moment it is read from disk so callers can render stale data while the
  /// network call is pending; the Future resolves once both have settled,
  /// throwing if no payload could be obtained at all.
  ///
  /// Pass [renew] for explicit user-triggered reloads to bypass the per-path
  /// TTL in [ListFilesCache] (the root listing is otherwise cached for a day).
  Future<ListFilesResponse> listFiles(
    String path, {
    void Function(ListFilesResponse)? onCacheData,
    void Function(Object)? onError,
    bool renew = false,
    void Function(int nextAttempt, int maxAttempts)? onRetry,
  }) {
    if (DemoMode.active) return Future.value(DemoFiles.listing(path));
    return resolveFromCache<ListFilesResponse>(
      (onUpdate, onError) => ListFilesCache(
        path: path,
        onUpdate: onUpdate,
        onCacheData: onCacheData,
        onError: onError,
        renew: renew,
        onRetry: onRetry,
      ),
      onError: onError,
      operationName: 'listFiles',
    );
  }

  Future<void> createFolder(String fullPath) async {
    if (DemoMode.active) return;
    final webdav = await WebdavApi.webdav;
    await webdav.mkcol(PathUri.parse(fullPath));
  }
}
