import 'dart:convert';
import 'dart:io';

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

import '../../errors/server_exception.dart';
import '../nextcloud_ocs.dart';
import 'nextcloud_sharing_capabilities.dart';

/// Fetches the current user's Nextcloud capabilities via OCS
/// `GET cloud/capabilities` and extracts the `files_sharing` block. This is the
/// per-user, group-aware source of truth the sharing UI gates on — no custom
/// backend involved.
class GetNextcloudCapabilities {
  Future<NextcloudSharingCapabilities> run() async {
    final endpoint = NextcloudOcs.uri(
      'cloud/capabilities',
      queryParameters: {'format': 'json'},
    );
    final response = await http.get(endpoint, headers: NextcloudOcs.headers());
    if (response.statusCode != HttpStatus.ok) {
      throw ServerException(
        statusCode: response.statusCode,
        technicalDetails: 'cloud/capabilities: ${response.body}',
      );
    }
    final decoded = jsonDecode(response.body) as Map<String, dynamic>;
    final data =
        (decoded['ocs'] as Map<String, dynamic>?)?['data']
            as Map<String, dynamic>?;
    final capabilities = data?['capabilities'] as Map<String, dynamic>?;
    final filesSharing = capabilities?['files_sharing'];
    if (filesSharing is! Map<String, dynamic>) {
      // Server doesn't advertise files_sharing (app disabled) — treat as no
      // sharing capability rather than failing the whole load.
      return const NextcloudSharingCapabilities();
    }
    final passwordPolicy = capabilities?['password_policy'];
    return NextcloudSharingCapabilities.fromFilesSharing(
      filesSharing,
      passwordPolicy: passwordPolicy is Map<String, dynamic>
          ? passwordPolicy
          : null,
    );
  }
}
