import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:sentinel_shield/core/permissions/permission_activation_state.dart';
import 'package:sentinel_shield/core/permissions/permission_capability.dart';
import 'package:sentinel_shield/core/permissions/permission_coordinator.dart';

class DeveloperModeActivationService {
  DeveloperModeActivationService(
    this._permissions, {
    FlutterSecureStorage? secureStorage,
  }) : _secureStorage = secureStorage ?? const FlutterSecureStorage();

  static const String _enabledKey = 'enterprise_developer_mode_enabled';
  static const String _consentVersionKey =
      'enterprise_permission_consent_version';

  final PermissionCoordinator _permissions;
  final FlutterSecureStorage _secureStorage;

  Future<bool> isEnabled() async =>
      await _secureStorage.read(key: _enabledKey) == 'true';

  Future<PermissionActivationState> enable({
    required bool userConfirmedDeviceOwnership,
    required bool acceptedPrivacyDisclosure,
    required String consentVersion,
  }) async {
    if (!userConfirmedDeviceOwnership || !acceptedPrivacyDisclosure) {
      throw StateError(
        'Device ownership and privacy disclosure must be confirmed.',
      );
    }
    if (consentVersion.trim().isEmpty) {
      throw ArgumentError.value(consentVersion, 'consentVersion');
    }

    await _secureStorage.write(key: _enabledKey, value: 'true');
    await _secureStorage.write(
      key: _consentVersionKey,
      value: consentVersion,
    );
    return _permissions.status(developerModeEnabled: true);
  }

  Future<PermissionActivationState> request(
    PermissionCapability capability,
  ) async {
    if (!await isEnabled()) {
      throw StateError('Enterprise developer mode is not enabled.');
    }
    return _permissions.requestCapability(
      capability,
      developerModeEnabled: true,
      disclosureAccepted: true,
    );
  }

  Future<void> disable() async {
    await _secureStorage.delete(key: _enabledKey);
    await _secureStorage.delete(key: _consentVersionKey);
  }
}
