import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:mypoint_flutter_app/core/utils/extensions/datetime_extensions.dart';
import 'package:mypoint_flutter_app/core/network/restful_api_client_all_request.dart';
import '../../core/network/restful_api_viewmodel.dart';
import 'history/transaction_category_model.dart';
import 'history/transaction_history_response_model.dart';

class TransactionsHistoryViewModel extends RestfulApiViewModel {
  var categories = RxList<TransactionCategoryModel>();
  var historyResponse = Rxn<TransactionHistoryResponse>();
  void Function(String message)? onShowAlertError;
  TransactionCategoryModel? categorySelected;
  DateTime date = DateTime.now();

  @override
  onInit() {
    super.onInit();
    _getCategories();
  }

  Future<void> _getCategories() async {
    await callApi<List<TransactionCategoryModel>>(
      request: () => client.getTransactionHistoryCategories(),
      onSuccess: (data, _) {
        categories.value = data;
        categorySelected = categories.isNotEmpty ? categories.first : null;
      },
      onFailure: (message, _, _) {
        onShowAlertError?.call(message);
      },
      onComplete: () {
        getTransactionHistoryResponse();
      },
    );
  }

  Future<void> getTransactionHistoryResponse() async {
    final body = {
      'category_code': categorySelected?.code ?? '',
      'date': date.toFormattedString(format: 'yyyy-MM'),
      'limit': 10000,
      'offset':0,
    };
    await callApi<TransactionHistoryResponse>(
      request: () => client.getTransactionHistoryResponse(body),
      onSuccess: (data, _) {
        historyResponse.value = data;
      },
      onFailure: (message, _, _) {
        onShowAlertError?.call(message);
      },
    );
  }
}
