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

@injectable
class WorkingAreasApiProvider {
  final ApiClient _apiClient;

  WorkingAreasApiProvider(this._apiClient);

  Stream<List<WorkingArea>> getAllWorkingAreas() async* {
    await for (var result
        in _apiClient.queryWithCache(schema: allWorkingAreas)) {
      if (result == null || result.data == null) continue;

      if (result.hasException) {
        throw Exception(result.exception.toString());
      }
      if (result.data?['working_areas'] == null) continue;

      yield result.data!['working_areas'].map<WorkingArea>((e) {
        return WorkingArea.fromJson(e);
      }).toList();
    }
  }

  Stream<List<WorkingArea>> getStaffWorkingAreas() async* {
    await for (var result
        in _apiClient.queryWithCache(schema: staffWorkingAreas)) {
      if (result == null || result.data == null) {
        continue;
      }
      if (result.hasException) {
        if (result.exception is OperationException) continue;
        throw Exception(result.exception.toString());
      }

      if (result.data?['me']?['working_areas'] == null) continue;

      yield result.data!['me']['working_areas'].map<WorkingArea>((e) {
        return WorkingArea.fromJson(e);
      }).toList();
    }
  }

  Future<void> putWorkingAreas(List<String> workingAreas) async {
    final Map<String, dynamic> variables = {
      'areas': workingAreas,
    };
    var result =
        await _apiClient.mutate(schema: syncWorkingAreas, body: variables);

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