import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/configs/constants.dart';
import 'package:mypoint_flutter_app/networking/api/affiliate_api.dart'
    deferred as affiliate_api;
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import '../../networking/restful_api_viewmodel.dart';
import '../affiliate/model/affiliate_brand_model.dart';
import '../affiliate/model/affiliate_category_model.dart';

class AffiliateCategoryGridViewModel extends RestfulApiViewModel {
  void Function((List<AffiliateBrandModel>, String) data)?
  onShowAffiliateBrandPopup;
  void Function(String message)? onShowAlertError;

  bool _affiliateLibLoaded = false;

  Future<void> _ensureAffiliateLibraryLoaded() async {
    if (_affiliateLibLoaded) return;
    await affiliate_api.loadLibrary();
    _affiliateLibLoaded = true;
  }

  Future<void> affiliateBrandGetListBuyCategory(
    AffiliateCategoryModel category,
  ) async {
    await callApi<List<AffiliateBrandModel>>(
      request: () async {
        await _ensureAffiliateLibraryLoaded();
        final api = affiliate_api.AffiliateApi(client);
        return api.affiliateBrandGetList(
          categoryCode: AffiliateCategoryModel.codeToJson(category.code),
        );
      },
      onSuccess: (data, _) {
        if (data.isNotEmpty) {
          onShowAffiliateBrandPopup?.call((data, category.name ?? ''));
        }
      },
      onFailure: (msg, _, _) async {
        onShowAlertError?.call(msg);
      },
    );
  }
}
