// import 'dart:convert';
// import 'package:flutter_secure_storage/flutter_secure_storage.dart';
// import 'package:pocketbase/pocketbase.dart';

// class PbAuthStore extends AuthStore {
//   final FlutterSecureStorage _storage;
//   final String _storageKey;

//   PbAuthStore({
//     FlutterSecureStorage? storage,
//     String key = 'pb_auth',
//   })  : _storage = storage ?? const FlutterSecureStorage(),
//         _storageKey = key,
//         super();

//   @override
//   Future<void> save(String newToken, dynamic newRecord) async {
//     super.save(newToken, newRecord);

//     final encoded = jsonEncode(<String, dynamic>{
//       'token': newToken,
//       'model': newRecord,
//     });

//     await _storage.write(key: _storageKey, value: encoded);
//   }

//   @override
//   void clear() {
//     super.clear();
//     _storage.delete(key: _storageKey);
//   }

//   Future<void> loadFromStorage() async {
//     final raw = await _storage.read(key: _storageKey);
//     if (raw != null && raw.isNotEmpty) {
//       try {
//         final decoded = jsonDecode(raw) as Map<String, dynamic>;
//         final token = decoded['token'] as String?;
//         final model = decoded['model'];

//         if (token != null && token.isNotEmpty) {
//           super.save(token, model);
//           return;
//         }
//       } catch (_) {
//         clear();
//       }
//     }

//     const legacyKey = 'auth_token';
//     final legacyToken = await _storage.read(key: legacyKey);
//     if (legacyToken != null && legacyToken.isNotEmpty) {
//       super.save(legacyToken, null);
//     }
//   }
// }
import 'dart:convert';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:pocketbase/pocketbase.dart';

class PbAuthStore extends AuthStore {
  final FlutterSecureStorage _storage;
  final String _saveKey = 'pb_auth';

  PbAuthStore({FlutterSecureStorage? storage})
      : _storage = storage ??
            const FlutterSecureStorage(
              aOptions: AndroidOptions(encryptedSharedPreferences: true),
            );

  @override
  Future<void> save(String token, dynamic model) async {
    super.save(token, model);

    final encoded = jsonEncode(<String, dynamic>{
      'token': token,
      'model': model,
    });

    await _storage.write(key: _saveKey, value: encoded);
  }

  @override
  Future<void> clear() async {
    super.clear();
    await _storage.delete(key: _saveKey);
  }

  // Diese Methode rufen wir VOR App-Start auf!
  Future<void> loadFromStorage() async {
    final raw = await _storage.read(key: _saveKey);
    if (raw != null && raw.isNotEmpty) {
      try {
        final decoded = jsonDecode(raw);
        final token = decoded['token'] as String? ?? '';
        final modelData = decoded['model'];

        dynamic model;
        if (modelData is Map<String, dynamic>) {
          if (modelData.containsKey('collectionId')) {
            model = RecordModel.fromJson(modelData);
          } else {
            model = RecordModel.fromJson(modelData);
            // model = AdminModel.fromJson(modelData);
          }
        }

        // super.save schreibt nur in den Speicher (RAM) des AuthStores,
        // löst aber kein erneutes 'save' (und damit write) aus.
        super.save(token, model);
      } catch (e) {
        // Daten korrupt? Löschen.
        await clear();
      }
    }
  }
}
