import 'package:riverpod_annotation/riverpod_annotation.dart';

import '../../teams/domain/team.dart';
import '../../teams/infrastructure/teams_repository.dart';

part 'admin_teams_notifier.g.dart';

/// Live Firestore-backed stream of every team (including pending and
/// rejected), used by the admin panel.
@riverpod
Stream<List<Team>> adminTeamsStream(AdminTeamsStreamRef ref) {
  final repo = ref.watch(teamsRepositoryProvider);
  return repo.adminWatchAllTeams();
}

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

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

  Future<void> save(Team team) async {
    final repo = ref.read(teamsRepositoryProvider);
    state = const AsyncLoading();
    state = await AsyncValue.guard(() => repo.updateTeam(team));
  }

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