import 'package:shared_preferences/shared_preferences.dart';

/// Resultado do quiz, sempre com os dois indicadores juntos — nunca faz
/// sentido guardar/ler um sem o outro.
class QuizResultData {
  const QuizResultData({
    required this.signs,
    required this.signsMax,
    required this.factors,
    required this.factorsMax,
  });

  final int signs;
  final int signsMax;
  final int factors;
  final int factorsMax;
}

class QuizPrefs {
  static const String _kSeenQuizKey = 'seen_oral_quiz_v1';
  static const String _kSignsKey = 'last_oral_quiz_signs_v2';
  static const String _kSignsMaxKey = 'last_oral_quiz_signs_max_v2';
  static const String _kFactorsKey = 'last_oral_quiz_factors_v2';
  static const String _kFactorsMaxKey = 'last_oral_quiz_factors_max_v2';

  static String _scopeKey(String base, String? scopeId) {
    final id = (scopeId ?? '').trim();
    if (id.isEmpty) return base;
    return '${base}_$id';
  }

  static Future<bool> hasSeenQuiz() async {
    final prefs = await SharedPreferences.getInstance();
    return prefs.getBool(_kSeenQuizKey) ?? false;
  }

  static Future<void> markQuizSeen() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_kSeenQuizKey, true);
  }

  static Future<void> saveLastResult(QuizResultData result) async {
    await saveLastResultForScope(scopeId: null, result: result);
  }

  static Future<void> saveLastResultForUser({
    required String userId,
    required QuizResultData result,
  }) async {
    await saveLastResultForScope(scopeId: userId, result: result);
  }

  static Future<void> saveLastResultForScope({
    required String? scopeId,
    required QuizResultData result,
  }) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setInt(_scopeKey(_kSignsKey, scopeId), result.signs);
    await prefs.setInt(_scopeKey(_kSignsMaxKey, scopeId), result.signsMax);
    await prefs.setInt(_scopeKey(_kFactorsKey, scopeId), result.factors);
    await prefs.setInt(
      _scopeKey(_kFactorsMaxKey, scopeId),
      result.factorsMax,
    );
  }

  static Future<QuizResultData?> getLastResult() =>
      getLastResultForScope(null);

  static Future<QuizResultData?> getLastResultForUser(String userId) =>
      getLastResultForScope(userId);

  static Future<QuizResultData?> getLastResultForScope(
    String? scopeId,
  ) async {
    final prefs = await SharedPreferences.getInstance();
    final signs = prefs.getInt(_scopeKey(_kSignsKey, scopeId));
    final signsMax = prefs.getInt(_scopeKey(_kSignsMaxKey, scopeId));
    final factors = prefs.getInt(_scopeKey(_kFactorsKey, scopeId));
    final factorsMax = prefs.getInt(_scopeKey(_kFactorsMaxKey, scopeId));
    if (signs == null ||
        signsMax == null ||
        factors == null ||
        factorsMax == null) {
      return null;
    }
    return QuizResultData(
      signs: signs,
      signsMax: signsMax,
      factors: factors,
      factorsMax: factorsMax,
    );
  }
}
