import 'package:injectable/injectable.dart';
import 'package:krow/core/application/clients/api/api_client.dart';
import 'package:krow/features/check_list/data/gql.dart';

@injectable
class CheckListApiProvider {
  CheckListApiProvider(this._apiClient);

  static const _verificationListKey = 'verification_check_list';

  final ApiClient _apiClient;

  Stream<Map<String, dynamic>> fetchCheckListWithCache() async* {
    await for (var result
        in _apiClient.queryWithCache(schema: getCheckListQuery)) {
      if (result == null || result.data == null) continue;

      if (result.hasException) {
        throw Exception(result.exception.toString());
      }

      if (result.data?[_verificationListKey] == null) continue;
      yield result.data?[_verificationListKey] ?? {};
    }
  }

  Future<Map<String, dynamic>> fetchCheckList() async {
    final result = await _apiClient.query(schema: getCheckListQuery);

    if (result.hasException) {
      throw Exception(result.exception.toString());
    }

    return result.data?[_verificationListKey] ?? {};
  }

  Future<void> submitVerification() async {
    var result = await _apiClient.mutate(schema: submitVerificationMutation);

    if (result.hasException) {
      throw Exception(result.exception.toString());
    }
  }
}
