/// Native (dart:io) slot-based save-game persistence.
library;

import 'dart:io';
import 'dart:typed_data';

import 'package:wolf_3d_dart/src/engine/save/save_game_persistence.dart';
import 'package:wolf_3d_dart/src/platform/platform_config_dir.dart';
import 'package:wolf_3d_dart/wolf_3d_data_types.dart';

/// Persists save-game slots as raw bytes under the platform config directory.
///
/// Files are stored in `<configDir>/saves/` and named
/// `SAVEGAM{slot}.{ext}` where `{ext}` follows the active game version.
///
/// Pass an explicit [directoryPath] to override the default (useful in tests).
class DefaultSaveGamePersistence extends SaveGamePersistence {
  DefaultSaveGamePersistence({String? directoryPath})
    : _directoryPath = directoryPath ?? '${platformConfigDir()}/saves';

  final String _directoryPath;

  @override
  Future<Uint8List?> load({
    required int slot,
    required GameVersion version,
  }) async {
    try {
      final File file = File(_slotPath(slot, version));
      if (!file.existsSync()) return null;
      return await file.readAsBytes();
    } catch (_) {
      return null;
    }
  }

  @override
  Future<bool> exists({
    required int slot,
    required GameVersion version,
  }) async {
    try {
      final File file = File(_slotPath(slot, version));
      return file.existsSync() && file.lengthSync() > 0;
    } catch (_) {
      return false;
    }
  }

  @override
  Future<void> save({
    required int slot,
    required GameVersion version,
    required Uint8List bytes,
  }) async {
    final Directory dir = Directory(_directoryPath);
    if (!dir.existsSync()) await dir.create(recursive: true);
    await File(_slotPath(slot, version)).writeAsBytes(bytes, flush: true);
  }

  String _slotPath(int slot, GameVersion version) {
    final String normalizedSlot = slot.clamp(0, 9).toString();
    return '$_directoryPath/SAVEGAM$normalizedSlot.${version.fileExtension}';
  }
}
