import 'package:riverpod_annotation/riverpod_annotation.dart';

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

part 'suggestions_repository.g.dart';

class SuggestionsRepository {
  SuggestionsRepository(this._api);

  final ApiClient _api;

  Future<void> submitSuggestion({
    required String text,
    required bool isAnonymous,
    String? userId,
    String? displayName,
  }) async {
    await _api.post('/suggestions/index.php', {
      'text': text,
      'is_anonymous': isAnonymous,
      'display_name': displayName ?? '',
    });
  }

  Future<List<Suggestion>> fetchUserSuggestions() async {
    final data = await _api.get('/suggestions/index.php');
    final list = (data['suggestions'] as List?) ?? [];
    return list.whereType<Map<String, dynamic>>().map(Suggestion.fromJson).toList();
  }

  Future<List<Suggestion>> fetchAllSuggestions() async {
    final data = await _api.get('/suggestions/index.php');
    final list = (data['suggestions'] as List?) ?? [];
    return list.whereType<Map<String, dynamic>>().map(Suggestion.fromJson).toList();
  }

  Future<void> updateStatus(String id, SuggestionStatus status) async {
    await _api.put(
      '/suggestions/detail.php',
      {'status': status.name},
      params: {'id': id},
    );
  }

  Future<void> deleteSuggestion(String id) async {
    await _api.delete('/suggestions/detail.php', params: {'id': id});
  }

  Stream<List<Suggestion>> watchUserSuggestions(String userId) async* {
    yield await fetchUserSuggestions();
    await for (final _ in Stream<void>.periodic(const Duration(seconds: 30))) {
      yield await fetchUserSuggestions();
    }
  }

  Stream<List<Suggestion>> watchAllSuggestions() async* {
    yield await fetchAllSuggestions();
    await for (final _ in Stream<void>.periodic(const Duration(seconds: 30))) {
      yield await fetchAllSuggestions();
    }
  }
}

@Riverpod(keepAlive: true)
SuggestionsRepository suggestionsRepository(SuggestionsRepositoryRef ref) {
  return SuggestionsRepository(ref.watch(apiClientProvider));
}
