import 'dart:developer';

import 'package:injectable/injectable.dart';
import 'package:krow/core/application/clients/api/api_client.dart';
import 'package:krow/core/data/models/staff/staff.dart';
import 'package:krow/core/data/models/staff_role.dart';
import 'package:krow/features/profile/profile_main/data/profile_gql.dart';

@injectable
class ProfileApiProvider {
  final ApiClient _apiClient;

  ProfileApiProvider({required ApiClient apiClient}) : _apiClient = apiClient;

  Future<List<StaffRole>> fetchUserProfileRoles() async {
    var result = await _apiClient.query(schema: getStaffProfileRolesQuery);
    if (result.hasException) {
      throw Exception(result.exception.toString());
    }

    return result.data!['staff_roles'].map<StaffRole>((e) {
      return StaffRole.fromJson(e);
    }).toList();
  }

  Stream<Staff> getMeWithCache() async* {
    await for (var response in _apiClient.queryWithCache(schema: getMeQuery)) {
      if (response == null || response.data == null) continue;

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

      try {
        final staffData = response.data?['me'] as Map<String, dynamic>? ?? {};
        if (staffData.isEmpty) continue;

        yield Staff.fromJson(staffData);
      } catch (except) {
        log(
          'Exception in StaffApi on getMeWithCache()',
          error: except,
        );
        continue;
      }
    }
  }
}
