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

class SecureAuthStore extends AuthStore {
  final FlutterSecureStorage _storage;
  final String _saveKey;

  SecureAuthStore({
    required FlutterSecureStorage storage,
    String saveKey = 'pb_auth',
  })  : _storage = storage,
        _saveKey = saveKey;

  @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: _saveKey, value: encoded);
  }

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

  Future<void> load() 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 model = decoded['model'];

        super.save(token, model);
      } catch (_) {
        await clear();
      }
    }
  }
}
