import 'package:english_learning/core/services/dio_client.dart';
import 'package:english_learning/features/learning/modules/feedback/models/feedback_model.dart';

class ExerciseRepository {
  final DioClient _dioClient;

  ExerciseRepository(this._dioClient);

  Future<Map<String, dynamic>> getExercises(
      String levelId, String token) async {
    try {
      final response = await _dioClient.getExercises(levelId, token);
      if (response.statusCode == 200) {
        return response.data['payload'];
      } else {
        throw Exception('Failed to load exercises');
      }
    } catch (e) {
      throw Exception('Error fetching exercises: $e');
    }
  }

  Future<Map<String, dynamic>> getStudentAnswers(
      String stdLearningId, String token) async {
    try {
      final response = await _dioClient.getStudentAnswers(stdLearningId, token);
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('Failed to load student answers');
      }
    } catch (e) {
      throw Exception('Error fetching student answers: $e');
    }
  }

  Future<Map<String, dynamic>> submitAnswersAndGetScore(
      List<Map<String, dynamic>> answers,
      String studentLearningId,
      String token) async {
    try {
      // Submit answers
      await _dioClient.submitExerciseAnswers(answers, token);

      // Get score
      final response = await _dioClient.getScore(studentLearningId, token);
      if (response.statusCode == 200) {
        return response.data['payload'];
      } else {
        throw Exception('Failed to get score');
      }
    } catch (e) {
      throw Exception('Error submitting answers and getting score: $e');
    }
  }

  Future<FeedbackModel> submitFeedback(
    String stdLearningId,
    String feedback,
    String token,
  ) async {
    try {
      final response = await _dioClient.studentFeedback(
        stdLearningId,
        feedback,
        token,
      );
      if (response.statusCode == 200) {
        return FeedbackModel.fromJson(response.data['payload']);
      } else {
        throw Exception('Failed to submit feedback');
      }
    } catch (e) {
      throw Exception('Error submitting feedback: $e');
    }
  }
}
