import 'dart:developer';

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

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

  final ApiClient _client;

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

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

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

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

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

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

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