// lib/features/notifications/services/notification_service.dart

import '../../../core/api/api_client.dart';
import '../../../core/api/api_endpoints.dart';
import '../models/notification_model.dart';

class NotificationService {
  final ApiClient _api = ApiClient();

  /// Fetch notifications for current user (paginated).
  Future<List<NotificationModel>> getNotifications({int page = 1, int pageSize = 20}) async {
    final res = await _api.post(
      ApiEndpoints.notificationList,
      body: {'page': page, 'page_size': pageSize},
    );
    final rawList = res['notifications'] ?? res['data'] ?? [];
    if (rawList is List) {
      return rawList
          .map((e) => NotificationModel.fromJson(Map<String, dynamic>.from(e as Map)))
          .toList();
    }
    return [];
  }

  /// Mark a single notification as read, or all if [notificationId] is null.
  Future<void> markAsRead({int? notificationId}) async {
    final body = <String, dynamic>{};
    if (notificationId != null) {
      body['notification_id'] = notificationId;
    } else {
      body['mark_all'] = true;
    }
    await _api.post(ApiEndpoints.notificationMarkRead, body: body);
  }

  /// Get unread notification count (lightweight).
  Future<int> getUnreadCount() async {
    final res = await _api.post(ApiEndpoints.notificationCount);
    return (res['unread_count'] as num?)?.toInt() ?? 0;
  }
}
