import 'package:injectable/injectable.dart';
import 'package:krow/core/application/clients/api/api_client.dart';
import 'package:krow/core/data/models/staff/full_address_model.dart';
import 'package:krow/features/profile/address/data/gql.dart';

@injectable
class AddressApiProvider {
  final ApiClient _apiClient;

  AddressApiProvider(this._apiClient);

  Stream<FullAddress?> getStaffAddress() async* {
    await for (var response
        in _apiClient.queryWithCache(schema: staffAddress)) {
      if (response == null) {
        continue;
      }

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

      final address =
          FullAddress.fromJson(response.data?['me']?['full_address'] ?? {});
      yield address;
    }
  }

  Future<void> putAddress(FullAddress address) async {
      final Map<String, dynamic> variables = {
        'input': address.toJson(),
      };

      var result =
          await _apiClient.mutate(schema: saveFullAddress, body: variables);

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