import 'dart:io';

import 'package:http/http.dart' as http;

import '../nextcloud_ocs.dart';
import 'search_files_response.dart';

/// Wraps the Nextcloud OCS Search Provider API for the `files` provider.
/// Endpoint: `/ocs/v2.php/search/providers/files/search`.
class SearchFiles {
  Future<SearchFilesResponse> run({
    required String term,
    int limit = 50,
    int? cursor,
  }) async {
    final endpoint = NextcloudOcs.uri(
      'search/providers/files/search',
      queryParameters: {
        'term': term,
        'limit': limit.toString(),
        if (cursor != null) 'cursor': cursor.toString(),
      },
    );
    final response = await http.get(endpoint, headers: NextcloudOcs.headers());
    if (response.statusCode != HttpStatus.ok) {
      throw Exception(
        'Files search failed with ${response.statusCode}: ${response.body}',
      );
    }
    final data = NextcloudOcs.decode(response.body)['data'] as Map<String, dynamic>;
    return SearchFilesResponse.fromJson(data);
  }
}
