import 'package:riverpod_annotation/riverpod_annotation.dart';

import '../../auth/application/auth_notifier.dart';
import '../domain/suggestion.dart';
import '../infrastructure/suggestions_repository.dart';

part 'suggestions_notifier.g.dart';

/// Tracks the submission lifecycle of the suggestion form.
///
/// State is an `AsyncValue<void>`:
///   * idle  → `AsyncData(null)` after [build]
///   * busy  → `AsyncLoading()` while a submit is in flight
///   * done  → `AsyncData(null)` after a successful submit
///   * error → `AsyncError(...)` on failure
@riverpod
class SuggestionsNotifier extends _$SuggestionsNotifier {
  @override
  Future<void> build() async {
    return;
  }

  /// Submits a suggestion. UI should already have validated [text] length
  /// before calling — this method does not re-validate.
  Future<void> submit({
    required String text,
    required bool isAnonymous,
    String? userId,
    String? displayName,
  }) async {
    final repo = ref.read(suggestionsRepositoryProvider);
    state = const AsyncLoading();
    state = await AsyncValue.guard(() async {
      await repo.submitSuggestion(
        text: text.trim(),
        isAnonymous: isAnonymous,
        userId: isAnonymous ? null : userId,
        displayName: isAnonymous ? null : displayName,
      );
    });
  }
}

/// Streams the current user's previously-submitted suggestions.
///
/// Emits an empty list when the user is signed out, so the UI can render a
/// stable widget tree without juggling auth-vs-stream loading states.
@riverpod
Stream<List<Suggestion>> userSuggestions(UserSuggestionsRef ref) async* {
  final auth = ref.watch(authNotifierProvider);
  final user = auth.valueOrNull;
  if (user == null) {
    yield <Suggestion>[];
    return;
  }
  final repo = ref.watch(suggestionsRepositoryProvider);
  yield* repo.watchUserSuggestions(user.uid);
}
