import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../api/api_client_provider.dart';

part 'auth_providers_provider.g.dart';

class AuthProvidersConfig {
  final bool google;
  final bool apple;
  final bool phone;

  const AuthProvidersConfig({
    required this.google,
    required this.apple,
    required this.phone,
  });

  /// Conservative fallback used when the network probe fails. Phone OTP is
  /// always available; social sign-in is hidden until the backend confirms.
  static const fallback = AuthProvidersConfig(
    google: false,
    apple: false,
    phone: true,
  );

  bool get hasAnySocial => google || apple;
}

/// Cached server-driven flag set for which auth entry points are wired up.
///
/// Replaces the old `--dart-define=ENABLE_SOCIAL_AUTH` build flag: the client
/// now reads `GET /api/shared/auth-providers` once on cold start and hides
/// Google/Apple buttons when the corresponding flag is `false`.
@Riverpod(keepAlive: true)
Future<AuthProvidersConfig> authProviders(Ref ref) async {
  try {
    final response = await ref.read(apiClientProvider).get('/api/shared/auth-providers');
    final data = response['data'] as Map<String, dynamic>?;
    if (data == null) return AuthProvidersConfig.fallback;
    final google = data['google'] as Map<String, dynamic>?;
    final apple = data['apple'] as Map<String, dynamic>?;
    final phone = data['phone'] as Map<String, dynamic>?;
    return AuthProvidersConfig(
      google: (google?['enabled'] as bool?) ?? false,
      apple: (apple?['enabled'] as bool?) ?? false,
      phone: (phone?['enabled'] as bool?) ?? true,
    );
  } catch (_) {
    return AuthProvidersConfig.fallback;
  }
}
