import 'dart:developer';

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

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

  final ApiClient _client;

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

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

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

  Future<LivePhotoData> uploadStaffLivePhoto(LivePhotoData data) async {
    var result = await _client.mutate(
      schema: uploadStaffLivePhotoSchema,
      body: {
        'file': await MultipartFile.fromPath(
          'file',
          data.imagePath ?? '',
        ),
      },
    );

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

    if (result.data == null || result.data!.isEmpty) {
      throw Exception('Missing Live photo response from server');
    }

    return LivePhotoData.fromJson(
      result.data?['upload_staff_live_photo'] as Map<String, dynamic>,
    );
  }
}
