import 'package:riverpod_annotation/riverpod_annotation.dart';

import '../../events/domain/event.dart';
import '../../events/infrastructure/events_repository.dart';

part 'admin_events_notifier.g.dart';

/// Live Firestore-backed stream of every event in the system, used by the
/// admin panel. The public-facing [eventsStreamProvider] still emits mocked
/// data; admins read straight through to the real collection.
@riverpod
Stream<List<Event>> adminEventsStream(AdminEventsStreamRef ref) {
  final repo = ref.watch(eventsRepositoryProvider);
  return repo.watchEvents();
}

/// Imperative wrapper around the events repository write methods. The notifier
/// is `AsyncValue<void>`-shaped so screens can wire it up the same way as the
/// existing auth/suggestions notifiers.
@riverpod
class AdminEventsNotifier extends _$AdminEventsNotifier {
  @override
  Future<void> build() async {}

  Future<String> create(Event event) async {
    final repo = ref.read(eventsRepositoryProvider);
    state = const AsyncLoading();
    try {
      final id = await repo.createEvent(event);
      state = const AsyncData(null);
      return id;
    } catch (e, st) {
      state = AsyncError(e, st);
      rethrow;
    }
  }

  Future<void> save(Event event) async {
    final repo = ref.read(eventsRepositoryProvider);
    state = const AsyncLoading();
    state = await AsyncValue.guard(() => repo.updateEvent(event));
  }

  Future<void> delete(String id) async {
    final repo = ref.read(eventsRepositoryProvider);
    state = const AsyncLoading();
    state = await AsyncValue.guard(() => repo.deleteEvent(id));
  }
}
