// lib/features/notifications/providers/notification_provider.dart

import 'package:flutter/foundation.dart';
import '../../../core/utils/error_utils.dart';
import '../models/notification_model.dart';
import '../services/notification_service.dart';

class NotificationProvider extends ChangeNotifier {
  final NotificationService _service = NotificationService();

  List<NotificationModel> notifications = [];
  int unreadCount = 0;
  bool loading = false;
  String? error;

  /// Load full notification list.
  Future<void> loadNotifications() async {
    loading = true;
    error = null;
    notifyListeners();
    try {
      notifications = await _service.getNotifications();
      unreadCount = notifications.where((n) => !n.isRead).length;
    } catch (e) {
      error = userFriendlyError(e);
    } finally {
      loading = false;
      notifyListeners();
    }
  }

  /// Lightweight count refresh (no full list fetch).
  Future<void> refreshUnreadCount() async {
    try {
      unreadCount = await _service.getUnreadCount();
      notifyListeners();
    } catch (_) {
      // Silently fail — badge just won't update
    }
  }

  /// Mark single notification as read.
  Future<void> markAsRead(int id) async {
    try {
      await _service.markAsRead(notificationId: id);
      final idx = notifications.indexWhere((n) => n.id == id);
      if (idx >= 0) {
        notifications[idx].isRead = true;
        unreadCount = notifications.where((n) => !n.isRead).length;
        notifyListeners();
      }
    } catch (e) {
      error = userFriendlyError(e);
      notifyListeners();
    }
  }

  /// Mark all as read.
  Future<void> markAllAsRead() async {
    try {
      await _service.markAsRead(); // null = mark all
      for (final n in notifications) {
        n.isRead = true;
      }
      unreadCount = 0;
      notifyListeners();
    } catch (e) {
      error = userFriendlyError(e);
      notifyListeners();
    }
  }
}
