import 'dart:convert';

import '../../model/account_data.dart';
import '../../model/endpoint_data.dart';

/// Shared headers and URI builder for Nextcloud OCS v2 endpoints. Used by
/// TalkApi, AutocompleteApi, FileSharingApi.
class NextcloudOcs {
  NextcloudOcs._();

  /// Decodes an OCS v2 JSON envelope and returns its `ocs` object (the wrapper
  /// every response nests its `meta`/`data` under).
  static Map<String, dynamic> decode(String raw) =>
      (jsonDecode(raw) as Map<String, dynamic>)['ocs'] as Map<String, dynamic>;

  static Map<String, String> headers() => {
    'Accept': 'application/json',
    'OCS-APIRequest': 'true',
    'Authorization': AccountData().getBasicAuthHeader(),
  };

  static Uri uri(String pathSuffix, {Map<String, dynamic>? queryParameters}) {
    final endpoint = EndpointData().nextcloud();
    return Uri.https(
      endpoint.domain,
      '${endpoint.path}/ocs/v2.php/$pathSuffix',
      queryParameters?.map((key, value) => MapEntry(key, value.toString())),
    );
  }
}
