import 'package:get/get.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 'models/affiliate_brand_detail_model.dart';

class AffiliateBrandDetailViewModel extends RestfulApiViewModel {
  final String brandId;

  AffiliateBrandDetailViewModel(this.brandId);

  void Function(String message)? onShowAlertError;
  final Rxn<AffiliateBrandDetailModel> brandDetailData =
      Rxn<AffiliateBrandDetailModel>();

  bool _affiliateLibLoaded = false;

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

  @override
  void onInit() {
    super.onInit();
    _fetchDetail();
  }

  Future<void> _fetchDetail() async {
    await callApi<AffiliateBrandDetailModel>(
      request: () async {
        await _ensureAffiliateLibraryLoaded();
        final api = affiliate_api.AffiliateApi(client);
        return api.getAffiliateBrandDetail(brandId);
      },
      onSuccess: (data, _) {
        brandDetailData.value = data;
      },
      onFailure: (msg, _, _) async {
        brandDetailData.value = null;
        onShowAlertError?.call(msg.isNotEmpty ? msg : Constants.commonError);
      },
    );
  }
}
