import 'package:dio/dio.dart';
import 'package:english_learning/core/services/dio_client.dart';
import 'package:english_learning/features/history/models/history_model.dart';

class HistoryRepository {
  final DioClient _dioClient;

  HistoryRepository(this._dioClient);

  Future<List<LearningHistory>> getLearningHistory(
    String sectionId,
    String token,
  ) async {
    try {
      final response = await _dioClient.getLearningHistory(
        sectionId,
        token,
        page: 1,
        limit: 10,
      );
      if (response.statusCode == 200 && response.data != null) {
        final List<dynamic> historyData = response.data['payload']['history'];
        if (historyData.isEmpty) {
          return []; // Mengembalikan list kosong jika tidak ada data
        }
        return historyData
            .map((json) => LearningHistory.fromJson(json))
            .toList();
      } else {
        throw Exception(
            'Failed to load learning history: ${response.statusMessage}');
      }
    } on DioException catch (e) {
      if (e.response?.statusCode == 404) {
        return [];
      } else if (e.response != null) {
        throw Exception('Server error: ${e.response?.statusMessage}');
      } else {
        throw Exception('Network error: ${e.message}');
      }
    } catch (e) {
      throw Exception('Unexpected error: $e');
    }
  }
}
