import 'package:riverpod_annotation/riverpod_annotation.dart';

import '../../brackets/domain/bracket.dart';
import '../../brackets/infrastructure/brackets_repository.dart';

part 'admin_brackets_notifier.g.dart';

/// Live Firestore-backed stream of every bracket, used by the admin panel.
@riverpod
Stream<List<Bracket>> adminBracketsStream(AdminBracketsStreamRef ref) {
  final repo = ref.watch(bracketsRepositoryProvider);
  return repo.watchBrackets();
}

/// Imperative wrapper around the brackets repository write methods.
@riverpod
class AdminBracketsNotifier extends _$AdminBracketsNotifier {
  @override
  Future<void> build() async {}

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

  Future<void> save(Bracket bracket) async {
    final repo = ref.read(bracketsRepositoryProvider);
    state = const AsyncLoading();
    state = await AsyncValue.guard(() => repo.updateBracket(bracket));
  }

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

  Future<void> updateMatch(
    String bracketId,
    String roundLabel,
    BracketMatch match,
  ) async {
    final repo = ref.read(bracketsRepositoryProvider);
    state = const AsyncLoading();
    state = await AsyncValue.guard(
      () => repo.updateMatch(bracketId, roundLabel, match),
    );
  }
}
