/// Platform-agnostic persistence contract for renderer settings.
library;

import 'dart:convert';

import 'package:wolf_3d_dart/src/engine/rendering/renderer_settings.dart';

/// Abstract contract that host adapters must implement to persist settings.
abstract class RendererSettingsPersistence {
  /// Loads previously saved settings, returning `null` on first run or error.
  Future<WolfRendererSettings?> load();

  /// Saves [settings] asynchronously; failures should be silently absorbed.
  Future<void> save(WolfRendererSettings settings);
}

/// Mixin that handles JSON encode/decode so adapters only need to implement
/// raw string read/write.
mixin JsonRendererSettingsPersistence on RendererSettingsPersistence {
  Future<String?> readRaw();
  Future<void> writeRaw(String json);

  @override
  Future<WolfRendererSettings?> load() async {
    try {
      final String? raw = await readRaw();
      if (raw == null || raw.isEmpty) {
        return null;
      }
      final Object? decoded = jsonDecode(raw);
      if (decoded is! Map<String, Object?>) {
        return null;
      }
      return WolfRendererSettings.fromJson(decoded);
    } catch (_) {
      return null;
    }
  }

  @override
  Future<void> save(WolfRendererSettings settings) async {
    try {
      await writeRaw(jsonEncode(settings.toJson()));
    } catch (_) {
      // Best-effort — never break the game loop on persistence failure.
    }
  }
}
