import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:softplayer_dart_proto/accounts/v1/accounts_v1.pbgrpc.dart';
import 'package:softplayer_dart_proto/test/v1/test_v1.pbgrpc.dart';
import 'package:softplayer_web/core/grpc/grpc_auth_interceptor.dart';
import 'package:softplayer_web/core/tokens/application/tokens_application.dart';

import 'grpc_channel_provider.dart';

final testServiceClientProvider = Provider<TestServiceClient>((ref) {
  final channel = ref.watch(grpcChannelProvider);
  final tokenState = ref.read(tokensControllerProvider).value;
  if (tokenState == null) {
    throw Exception("Token state is not initialized");
  }

  return TestServiceClient(
    channel,
    interceptors: [
      AuthInterceptor(
        getAccessToken: tokenState.getAccessToken,
        getRefreshToken: tokenState.getRefreshToken,
      ),
    ],
  );
});

final accountsServiceClientProvider = Provider<AccountsServiceClient>((ref) {
  final channel = ref.watch(grpcChannelProvider);
  final tokenState = ref.read(tokensControllerProvider).value;
  if (tokenState == null) {
    throw Exception("Token state is not initialized");
  }
  return AccountsServiceClient(
    channel,
    interceptors: [
      AuthInterceptor(
        getAccessToken: tokenState.getAccessToken,
        getRefreshToken: tokenState.getRefreshToken,
      ),
    ],
  );
});

final publicAccountsServiceClientProvider =
    Provider<PublicAccountsServiceClient>((ref) {
      final channel = ref.watch(grpcChannelProvider);
      return PublicAccountsServiceClient(channel);
    });

final refreshSessionServiceClientProvider =
    Provider<RefreshSessionServiceClient>((ref) {
      final channel = ref.watch(grpcChannelProvider);
      return RefreshSessionServiceClient(channel);
    });
