import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../core/network/dio_client.dart';
import '../data/models/announcement/announcement.dart';
import '../data/services/announcement_service.dart';

const _kShownPopupIdsKey = 'announcement_popup_shown_ids';

/// 系统弹窗公告 Provider — 返回尚未展示过的弹窗公告列表（按发布时间从近到远）
final announcementPopupProvider =
    FutureProvider.autoDispose<List<AnnouncementBean>>((ref) async {
  final dio = ref.read(dioClientProvider);
  final beans = await AnnouncementService(dio).getPopupAnnouncements();
  if (beans.isEmpty) return [];

  final prefs = await SharedPreferences.getInstance();
  final shownIds = prefs.getStringList(_kShownPopupIdsKey) ?? [];

  return beans
      .where((b) => b.isShow && b.id.isNotEmpty && !shownIds.contains(b.id))
      .toList();
});

/// 标记弹窗已显示，记录 id（最多保留最近 100 条，防止无限增长）
Future<void> markPopupShown(String id) async {
  final prefs = await SharedPreferences.getInstance();
  final shownIds = prefs.getStringList(_kShownPopupIdsKey) ?? [];
  if (!shownIds.contains(id)) {
    shownIds.add(id);
    if (shownIds.length > 100) {
      shownIds.removeRange(0, shownIds.length - 100);
    }
    await prefs.setStringList(_kShownPopupIdsKey, shownIds);
  }
}
