import 'package:injectable/injectable.dart';
import 'package:krow/core/application/clients/api/api_client.dart';
import 'package:krow/features/profile/emergency_contacts/data/gql_schemas.dart';
import 'package:krow/features/profile/emergency_contacts/data/models/emergency_contact_model.dart';

@injectable
class EmergencyContactApiProvider {
  final ApiClient _apiClient;

  EmergencyContactApiProvider(this._apiClient);

  Stream<List<EmergencyContactModel>> getStaffEmergencyContacts() async* {
    await for (var response in _apiClient.queryWithCache(
      schema: getEmergencyContactsQuerySchema,
    )) {
      if (response == null || response.data == null) continue;

      if (response.data == null || response.data!.isEmpty) {
        if (response.source?.name == 'cache') continue;

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

      final contactsData =
          (response.data?['me'] as Map<String, dynamic>?)?['emergency_contacts']
                  as List<dynamic>? ??
              [];

      yield [
        for (final contact in contactsData)
          EmergencyContactModel.fromJson(
            contact as Map<String, dynamic>? ?? {},
          ),
      ];
    }
  }

  Future<List<EmergencyContactModel>?> updateEmergencyContacts(
    List<EmergencyContactModel> contacts,
  ) async {
    var result = await _apiClient.mutate(
      schema: updateEmergencyContactsMutationSchema,
      body: {
        'input': [
          for (final contact in contacts) contact.toJson(),
        ],
      },
    );

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

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

    //TODO(Heorhii) add contacts return
    return null;
  }
}
