import 'package:asciineverdie/src/core/model/game_state.dart';
import 'package:asciineverdie/src/core/model/monetization_state.dart';
import 'package:asciineverdie/src/core/model/save_data.dart';
import 'package:asciineverdie/src/core/storage/save_repository.dart';
import 'package:asciineverdie/src/core/storage/save_service.dart'
    show SaveFileInfo;

/// Coordinates saving/loading GameState using SaveRepository.
class SaveManager {
  SaveManager(this._repo);

  final SaveRepository _repo;
  static const String defaultFileName = 'progress.pqf';

  /// Save current game state to disk. [fileName] may be absolute or relative.
  /// Returns outcome with error on failure.
  ///
  /// [monetization] 저장 시 lastPlayTime을 현재 시간으로 자동 업데이트
  Future<SaveOutcome> saveState(
    GameState state, {
    String? fileName,
    bool cheatsEnabled = false,
    MonetizationState? monetization,
  }) {
    // lastPlayTime을 현재 시간으로 업데이트
    final updatedMonetization = (monetization ?? MonetizationState.initial())
        .copyWith(lastPlayTime: DateTime.now());

    final save = GameSave.fromState(
      state,
      cheatsEnabled: cheatsEnabled,
      monetization: updatedMonetization,
    );
    return _repo.save(save, fileName ?? defaultFileName);
  }

  /// Load game state from disk. [fileName] may be absolute (e.g., file picker).
  /// Returns outcome + optional state + cheatsEnabled flag + monetization state.
  Future<(SaveOutcome, GameState?, bool, MonetizationState?)> loadState({
    String? fileName,
  }) async {
    final (outcome, save) = await _repo.load(fileName ?? defaultFileName);
    if (!outcome.success || save == null) {
      return (outcome, null, false, null);
    }
    return (outcome, save.toState(), save.cheatsEnabled, save.monetization);
  }

  /// 저장 파일 목록 조회
  Future<List<SaveFileInfo>> listSaves() => _repo.listSaves();

  /// 저장 파일 삭제
  Future<SaveOutcome> deleteSave({String? fileName}) {
    return _repo.deleteSave(fileName ?? defaultFileName);
  }

  /// 저장 파일 존재 여부 확인
  Future<bool> saveExists({String? fileName}) {
    return _repo.saveExists(fileName ?? defaultFileName);
  }
}
