import 'package:flutter_riverpod/flutter_riverpod.dart';

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

class AnnouncementUnreadState {
  final bool isLoaded;
  final int unreadCount;
  final bool hasUnread;
  final int? latestId;
  final List<int> readIds;

  const AnnouncementUnreadState({
    this.isLoaded = false,
    this.unreadCount = 0,
    this.hasUnread = false,
    this.latestId,
    this.readIds = const [],
  });

  /// 未加载成功时视为已读（两边都不显示红点，保持一致）
  bool isRead(int announcementId) =>
      !isLoaded || readIds.contains(announcementId);
}

/// 公告未读数 Provider —— 未登录返回零；登录后请求 unread-count
final announcementUnreadProvider =
    FutureProvider<AnnouncementUnreadState>((ref) async {
  final loggedIn = ref.watch(isLoggedInProvider);
  if (!loggedIn) {
    return const AnnouncementUnreadState();
  }
  final dio = ref.read(dioClientProvider);
  try {
    final r = await AnnouncementService(dio).getUnreadCount();
    return AnnouncementUnreadState(
      isLoaded: true,
      unreadCount: r.unreadCount,
      hasUnread: r.hasUnread,
      latestId: r.latestId,
      readIds: r.readIds,
    );
  } catch (_) {
    return const AnnouncementUnreadState(); // isLoaded=false，两边都不显示红点
  }
});

/// 标记指定公告为已读并刷新未读数
Future<void> markAnnouncementsRead(WidgetRef ref, {required int id}) async {
  final loggedIn = ref.read(isLoggedInProvider);
  if (!loggedIn) return;
  final dio = ref.read(dioClientProvider);
  try {
    await AnnouncementService(dio).markRead(id);
  } catch (_) {
    // ignore
  }
  ref.invalidate(announcementUnreadProvider);
}
