import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/core/network/api/notification_api.dart' deferred as notification_api;
import '../../app/config/constants.dart';
import '../../core/network/restful_api_viewmodel.dart';
import 'models/notification_detail_model.dart';

class NotificationDetailViewModel extends RestfulApiViewModel {
  var notification = Rxn<NotificationDetailModel>();
  void Function(String message)? onShowAlertError;

  bool _notificationApiLoaded = false;

  Future<void> _ensureNotificationApiLoaded() async {
    if (_notificationApiLoaded) return;
    await notification_api.loadLibrary();
    _notificationApiLoaded = true;
  }

  Future<void> fetchNotificationDetail({String? id, NotificationDetailModel? data}) async {
    if (data != null) {
      notification.value = data;
      return;
    }
    if (id == null) return;
    await callApi<NotificationDetailResponseModel>(
      request: () async {
        await _ensureNotificationApiLoaded();
        final api = notification_api.NotificationApi(client);
        return api.getNotificationDetail(id);
      },
      onSuccess: (data, _) {
        final notify = data.notification;
        if (notify != null) {
          notification.value = data.notification;
        } else {
          onShowAlertError?.call(Constants.commonError);
        }
      },
      onFailure: (msg, _, _) async {
        onShowAlertError?.call(msg);
      },
    );
  }
}
