import 'dart:developer';

import 'package:injectable/injectable.dart';
import 'package:krow/core/application/clients/api/api_client.dart';
import 'package:krow/features/profile/inclusive/data/gql_shemas.dart';
import 'package:krow/features/profile/inclusive/data/models/inclusive_info_model.dart';

@injectable
class StaffInclusivityApiProvider {
  StaffInclusivityApiProvider(this._client);

  final ApiClient _client;

  Stream<InclusiveInfoModel> getStaffInclusivityInfoWithCache() async* {
    await for (var response in _client.queryWithCache(
      schema: getStaffInclusivityInfoSchema,
    )) {
      if (response == null || response.data == null) continue;

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

      try {
        yield InclusiveInfoModel.fromJson(
          (response.data?['me'] as Map<String, dynamic>?)?['accessibility'] ??
              {},
        );
      } catch (except) {
        log(
          'Exception in StaffInclusivityApiProvider '
          'on getStaffInclusivityInfoWithCache()',
          error: except,
        );
        continue;
      }
    }
  }

  Future<InclusiveInfoModel?> updateStaffInclusivityInfoInfo(
    InclusiveInfoModel data,
  ) async {
    var result = await _client.mutate(
      schema: updateStaffInclusivityMutationSchema,
      body: {
        'input': data.toJson(),
      },
    );

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

    if (result.data == null || result.data!.isEmpty) return null;

    return InclusiveInfoModel.fromJson(
      (result.data?['update_staff_accessibilities']
              as Map<String, dynamic>?)?['accessibility'] ??
          {},
    );
  }
}
