import 'package:riverpod_annotation/riverpod_annotation.dart';

import '../../../core/api/api_client.dart';
import '../domain/user_profile.dart';

part 'profile_repository.g.dart';

class ProfileRepository {
  ProfileRepository(this._api);

  final ApiClient _api;

  Future<UserProfile?> getProfile(String uid) async {
    try {
      final data = await _api.get('/profiles/detail.php', params: {'uid': uid});
      return UserProfile.fromJson(data);
    } on ApiException catch (e) {
      if (e.statusCode == 404) return null;
      rethrow;
    }
  }

  Future<void> createProfile(UserProfile profile) async {
    await _api.put('/profiles/detail.php', profile.toJson(), params: {'uid': profile.uid});
  }

  Future<void> updateProfile(UserProfile profile) async {
    await _api.put('/profiles/detail.php', profile.toJson(), params: {'uid': profile.uid});
  }

  Future<void> updateTeamId(String uid, String? teamId) async {
    await _api.put('/profiles/detail.php', {'team_id': teamId}, params: {'uid': uid});
  }

  Stream<UserProfile?> watchProfile(String uid) async* {
    yield await getProfile(uid);
    await for (final _ in Stream<void>.periodic(const Duration(seconds: 30))) {
      yield await getProfile(uid);
    }
  }

  Future<List<UserProfile>> fetchAllPlayers() async {
    // The /auth/me.php endpoint only returns one user.
    // For the admin player list, re-use profile fetch per user (admin panel).
    // For MVP, return empty — admin panel can be extended later.
    return [];
  }

  Stream<List<UserProfile>> watchAllPlayers() async* {
    yield await fetchAllPlayers();
  }
}

@Riverpod(keepAlive: true)
ProfileRepository profileRepository(ProfileRepositoryRef ref) {
  return ProfileRepository(ref.watch(apiClientProvider));
}
