import 'package:riverpod_annotation/riverpod_annotation.dart';

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

part 'teams_notifier.g.dart';

/// Resolves a single [Team] by id out of the teams stream. Returns null while
/// loading or if no team matches.
@riverpod
Team? teamById(TeamByIdRef ref, String id) {
  final teams = ref.watch(teamsStreamProvider).valueOrNull;
  if (teams == null) return null;
  for (final team in teams) {
    if (team.id == id) return team;
  }
  return null;
}

/// Streams every join request for [teamId]. Used by the manager dashboard.
@riverpod
Stream<List<JoinRequest>> joinRequestsForTeam(
  JoinRequestsForTeamRef ref,
  String teamId,
) {
  return ref.watch(teamsRepositoryProvider).watchJoinRequestsForTeam(teamId);
}

/// Streams every join request submitted by [playerId]. Used to decide
/// whether to show "Request pending" on a team detail page.
@riverpod
Stream<List<JoinRequest>> joinRequestsForPlayer(
  JoinRequestsForPlayerRef ref,
  String playerId,
) {
  return ref
      .watch(teamsRepositoryProvider)
      .watchJoinRequestsForPlayer(playerId);
}
