import '../../network_api_service/api_service/api_service.dart';
import '../../network_api_service/api_urls/api_urls.dart';
import '../models/scan_history_model.dart';
import '../models/scan_history_details_model.dart';


class ScanHistoryRepository {
  final ApiService _apiService = ApiService();

  /// Fetch Scan History List with filters
  Future<List<ScanHistory>> fetchScanHistory({String? date, String? status}) async {
    try {
      Map<String, dynamic> queryParameters = {};
      if (date != null) queryParameters['date'] = date;
      if (status != null && status != 'all') queryParameters['status'] = status.toLowerCase();

      final response = await _apiService.get(
        ApiUrls.scanHistory,
        queryParameters: queryParameters,
      );

      final ScanHistoryResponse scanResponse =
      ScanHistoryResponse.fromJson(response.data);

      return scanResponse.data;
    } catch (e) {
      throw Exception('Failed to fetch scan history: $e');
    }
  }

  /// Fetch Scan History Details by ID
  Future<ScanHistoryDetails> fetchScanHistoryDetails(int id) async {
    try {
      final response = await _apiService.get("${ApiUrls.scanHistory}/$id");

      // Check if data is wrapped in a 'data' key or is at the root
      final dynamic rawData = response.data;
      if (rawData is Map<String, dynamic>) {
        if (rawData.containsKey('data')) {
           return ScanHistoryDetails.fromJson(rawData['data']);
        }
        return ScanHistoryDetails.fromJson(rawData);
      }
      throw Exception('Invalid response format');
    } catch (e) {
      throw Exception('Failed to fetch scan history details: $e');
    }
  }
}