// lib/src/features/backup/domain/backup_service.dart
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:slrpg_app/src/shared/data/repositories/cycle_repository.dart';
import 'package:slrpg_app/src/shared/data/repositories/user_repository.dart';
import 'package:slrpg_app/src/shared/data/repositories/workout_repository.dart';
import '../../../shared/data/local/app_database.dart';

class BackupService {
  final AppDatabase _db;
  final UserRepository _userRepo;
  final CycleRepository _cycleRepository;
  final WorkoutRepository _workoutRepository;

  BackupService(
      this._db, this._userRepo, this._cycleRepository, this._workoutRepository);

  Future<File> createBackup() async {
    final userData = await _userRepo.getLocalUser();
    final workouts = await _workoutRepository.getAllWorkouts();
    final cycles = await _cycleRepository.getAllCycles();
    final inventory = await _userRepo.getInventorySettingsAsync();

    final backupData = {
      'version': '1.0.0',
      'exportDate': DateTime.now().toIso8601String(),
      'user': userData?.toJson(),
      'workouts': workouts.map((w) => w.toJson()).toList(),
      'cycles': cycles.map((c) => c.toJson()).toList(),
      'inventory': inventory,
    };

    final jsonString = const JsonEncoder.withIndent('  ').convert(backupData);

    final directory = await getTemporaryDirectory();
    final timestamp = DateTime.now().millisecondsSinceEpoch;
    final file = File('${directory.path}/slrpg_export_$timestamp.json');

    await file.writeAsString(jsonString);

    return file;
  }
}
