import 'package:built_value/json_object.dart';
import 'package:latlong2/latlong.dart';

import '../domain/place_models.dart';
import 'graphql/__generated__/create_voice_experience.req.gql.dart';
import 'graphql/__generated__/voice_experiences.req.gql.dart';
import 'mapflow_data_mappers.dart';
import 'mapflow_graphql_client.dart';

class VoiceExperiencesRepository {
  const VoiceExperiencesRepository({required MapflowGraphqlClient client})
    : _client = client;

  final MapflowGraphqlClient _client;

  Future<void> createVoiceExperience({
    required String googlePlaceId,
    required String googleName,
    required LatLng coordinate,
    required String? googlePrimaryType,
    required List<String> googleTypes,
    required int durationSeconds,
    required String audioObjectKey,
    required String audioContentBase64,
    required String audioMimeType,
    required bool addToFavorites,
    required Map<String, dynamic> recordingPayload,
    required List<String> promptHintsShown,
  }) async {
    if (!_client.hasTelegramAuth) {
      throw StateError('Telegram authorization is required.');
    }

    await _client.request(
      GCreateVoiceExperienceReq((b) {
        b.vars.input
          ..googlePlaceId = googlePlaceId
          ..googleName = googleName
          ..latitude = coordinate.latitude
          ..longitude = coordinate.longitude
          ..googlePrimaryType = googlePrimaryType
          ..googleTypes.addAll(googleTypes)
          ..durationSeconds = durationSeconds
          ..audioObjectKey = audioObjectKey
          ..audioContentBase64 = audioContentBase64
          ..audioMimeType = audioMimeType
          ..addToFavorites = addToFavorites
          ..recordingPayload = JsonObject(recordingPayload)
          ..promptHintsShown.addAll(promptHintsShown);
      }),
    );
  }

  Future<List<VoiceExperienceDebug>> fetchVoiceExperiences() async {
    final data = await _client.request(GVoiceExperiencesReq());
    return data.voiceExperiences
        .map(voiceExperienceDebugFromVoiceExperience)
        .toList();
  }
}
