import 'dart:async';

import 'package:riverpod_annotation/riverpod_annotation.dart';

import '../../../core/api/api_client_provider.dart';
import '../models/request_history_entry.dart';

part 'request_history_notifier.g.dart';

@Riverpod(keepAlive: true)
class RequestHistory extends _$RequestHistory {
  @override
  FutureOr<List<RequestHistoryEntry>> build() async {
    return _fetch();
  }

  Future<void> refresh() async {
    state = const AsyncLoading();
    state = await AsyncValue.guard(_fetch);
  }

  Future<List<RequestHistoryEntry>> _fetch() async {
    final api = ref.read(apiClientProvider);
    final response = await api.get('/api/mitra/chat-requests/recent');
    final items = (response['data'] as List<dynamic>).cast<Map<String, dynamic>>();
    return items.map(RequestHistoryEntry.fromJson).toList();
  }

  RequestHistoryEntry? findById(String notificationId) {
    final list = state.valueOrNull;
    if (list == null) return null;
    for (final e in list) {
      if (e.notificationId == notificationId) return e;
    }
    return null;
  }
}
