import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/api/api_providers.dart';
import '../../../core/platform/platform_providers.dart';
import '../../../core/auth/jwt_decoder.dart';
import 'auth_repository.dart';

final authRepositoryProvider = Provider<AuthRepository>((ref) {
  return AuthRepository(
    ref.watch(apiClientProvider),
    ref.watch(tokenStorageProvider),
  );
});

final authStateProvider = AsyncNotifierProvider<AuthNotifier, String?>(() {
  return AuthNotifier();
});

class AuthNotifier extends AsyncNotifier<String?> {
  @override
  Future<String?> build() async {
    return ref.watch(authRepositoryProvider).getToken();
  }

  Future<void> login(String username, String password) async {
    state = const AsyncLoading();
    state = await AsyncValue.guard(
      () => ref.read(authRepositoryProvider).login(username, password),
    );
  }

  Future<void> logout() async {
    await ref.read(authRepositoryProvider).logout();
    state = const AsyncData(null);
  }
}

/// Synchronously derived provider — true when the current token has role == 'admin'.
final isAdminProvider = Provider<bool>((ref) {
  final token = ref.watch(authStateProvider).maybeWhen(data: (t) => t, orElse: () => null);
  return jwtIsAdmin(token);
});
