import 'dart:io';

import 'package:asciineverdie/src/core/model/save_data.dart';
import 'package:asciineverdie/src/core/storage/save_integrity.dart';
import 'package:asciineverdie/src/core/storage/save_service.dart';
import 'package:path_provider/path_provider.dart';

class SaveOutcome {
  const SaveOutcome.success([this.error]) : success = true;
  const SaveOutcome.failure(this.error) : success = false;

  final bool success;
  final String? error;
}

/// High-level save/load wrapper that resolves platform storage paths.
class SaveRepository {
  SaveRepository() : _service = null;

  SaveService? _service;

  Future<void> _ensureService() async {
    if (_service != null) return;
    final dir = await getApplicationSupportDirectory();
    _service = SaveService(baseDir: dir);
  }

  Future<SaveOutcome> save(GameSave save, String fileName) async {
    try {
      await _ensureService();
      await _service!.save(save, fileName);
      return const SaveOutcome.success();
    } on FileSystemException catch (e) {
      final reason = e.osError?.message ?? e.message;
      return SaveOutcome.failure('Unable to save file: $reason');
    } catch (e) {
      return SaveOutcome.failure(e.toString());
    }
  }

  Future<(SaveOutcome, GameSave?)> load(String fileName) async {
    try {
      await _ensureService();
      final data = await _service!.load(fileName);
      return (const SaveOutcome.success(), data);
    } on FileSystemException catch (e) {
      final reason = e.osError?.message ?? e.message;
      return (SaveOutcome.failure('Unable to load save: $reason'), null);
    } on SaveIntegrityException catch (e) {
      return (SaveOutcome.failure('Tampered save file: ${e.message}'), null);
    } on FormatException catch (e) {
      return (SaveOutcome.failure('Corrupted save file: ${e.message}'), null);
    } catch (e) {
      return (SaveOutcome.failure(e.toString()), null);
    }
  }

  /// 저장 파일 목록 조회
  Future<List<SaveFileInfo>> listSaves() async {
    try {
      await _ensureService();
      return await _service!.listSaves();
    } catch (e) {
      return [];
    }
  }

  /// 저장 파일 삭제
  Future<SaveOutcome> deleteSave(String fileName) async {
    try {
      await _ensureService();
      await _service!.deleteSave(fileName);
      return const SaveOutcome.success();
    } on FileSystemException catch (e) {
      final reason = e.osError?.message ?? e.message;
      return SaveOutcome.failure('Unable to delete save: $reason');
    } catch (e) {
      return SaveOutcome.failure(e.toString());
    }
  }

  /// 저장 파일 존재 여부 확인
  Future<bool> saveExists(String fileName) async {
    try {
      await _ensureService();
      return await _service!.exists(fileName);
    } catch (e) {
      return false;
    }
  }
}
