import 'dart:developer';

import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:hub/features/storage/index.dart';

class SecureStorage implements BaseStorage {
  SecureStorage._();

  static final SecureStorage instance = SecureStorage._();

  late final FlutterSecureStorage _secureStorage;
  bool _isInitialized = false;

  @override
  Future<void> init() async {
    if (_isInitialized) return;
    _secureStorage = const FlutterSecureStorage();
    _isInitialized = true;
  }

  @override
  Future<String?> get(String key) async {
    return await _secureStorage.read(key: key);
  }

  @override
  Future<void> set<T>(String key, T value) async {
    log('Setting value: $value');
    try {
      await _secureStorage.write(key: key, value: value.toString());
    } catch (e, s) {
      log('Error setting value: $e', stackTrace: s);
    }
  }

  @override
  Future<void> delete(String key) async {
    await _secureStorage.delete(key: key);
  }

  @override
  Future<void> clearAll() async {
    log('Clearing SecureStorage');
    try {
      await _secureStorage.deleteAll(
        aOptions: AndroidOptions(),
        iOptions: IOSOptions(),
      );
    } catch (e, s) {
      log('Error clearing all: $e', stackTrace: s);
    }
  }
}
