import 'package:mypoint_flutter_app/core/network/api/affiliate_api.dart' deferred as affiliate_api;
import '../../core/network/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);
      },
    );
  }
}
