/*
 * ac_ops - exercises several ac_svr ONLINE services (not the chain) under ONE
 * global XA transaction, to prove the module server's advertised services work
 * and commit. Usage: ac_ops <purchase_id> [merchant] [amount] [bizdate]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include <ubf.h>
#include "acq.fd.h"

static long callsvc(const char *svc, UBFH **b)
{
    long rlen = 0;
    if (tpcall((char *)svc, (char *)*b, 0L, (char **)b, &rlen, 0L) < 0) {
        fprintf(stderr, "tpcall(%s) FAIL: %s\n", svc, tpstrerror(tperrno));
        return -1;
    }
    return 0;
}

int main(int argc, char **argv)
{
    long pid     = (argc > 1) ? atol(argv[1]) : 1;
    const char *merch   = (argc > 2) ? argv[2] : "M0001";
    long amount  = (argc > 3) ? atol(argv[3]) : 1000000;
    const char *bizdate = (argc > 4) ? argv[4] : "2026-07-19";
    UBFH *b;
    long cnt = 0, adj = 0, months = 0, delta = 100;
    char st[16] = "";
    BFLDLEN l;

    if (tpinit(NULL) < 0) { fprintf(stderr, "tpinit FAIL: %s\n", tpstrerror(tperrno)); return 1; }
    if (tpopen() < 0)     { fprintf(stderr, "tpopen FAIL: %s\n", tpstrerror(tperrno)); return 1; }
    b = (UBFH *)tpalloc("UBF", NULL, 4096);
    if (!b) { fprintf(stderr, "tpalloc FAIL\n"); return 1; }

    Bchg(b, T_PURCHASE_ID, 0, (char *)&pid, 0L);
    Bchg(b, T_MERCHANT, 0, (char *)merch, 0L);
    Bchg(b, T_AMOUNT, 0, (char *)&amount, 0L);
    Bchg(b, T_BIZDATE, 0, (char *)bizdate, 0L);
    Bchg(b, T_DELTA, 0, (char *)&delta, 0L);
    Bchg(b, T_INSTALL_N, 0, (char *)(long[]){3}, 0L);
    Bchg(b, T_REASON, 0, "OPS_TEST", 0L);

    if (tpbegin(60, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    if (callsvc("ACQ_DUPCHK", &b) < 0)  { tpabort(0); return 1; }
    Bget(b, T_COUNT, 0, (char *)&cnt, 0L);
    if (callsvc("ACQ_FEEADJ", &b) < 0)  { tpabort(0); return 1; }
    Bget(b, T_ADJ, 0, (char *)&adj, 0L);
    if (callsvc("ACQ_INSTALL", &b) < 0) { tpabort(0); return 1; }
    Bget(b, T_COUNT, 0, (char *)&months, 0L);
    if (callsvc("ACQ_STATUS", &b) < 0)  { tpabort(0); return 1; }
    l = sizeof(st); Bget(b, T_STATUS, 0, st, &l);

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }

    printf(">>> ac_ops COMMIT: pid=%ld dupchk_count=%ld fee_adj_id=%ld install_rows=%ld status=%s\n",
           pid, cnt, adj, months, st);

    tpfree((char *)b); tpclose(); tpterm();
    return 0;
}
