/*
 * cm_bizday_roll_batch.pgc - cm 영업일 롤 배치 (XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction. Reads cm_param BIZ_DATE, advances it to the next 영업일 (주말=common
 * util로 skip, 휴일=cm_holiday로 skip), writes it back via the dbio layer, then
 * tpcommit drives XA 2PC. Usage: cm_bizday_roll_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "cm_dbio.h"
#include "acq_common.h"

int main(int argc, char **argv)
{
    char cur[16], nxt[16];
    int hol, guard = 0;

    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; }
    if (tpbegin(60, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    if (cmdb_get_param("BIZ_DATE", cur) < 0) {
        fprintf(stderr, "BIZ_DATE 조회 실패\n"); tpabort(0); return 1;
    }

    /* 다음 영업일: 주말 + 휴일 모두 건너뜀 */
    do {
        if (acq_next_bizday(cur, nxt) < 0) { fprintf(stderr, "next_bizday 파싱 실패: %s\n", cur); tpabort(0); return 1; }
        strncpy(cur, nxt, sizeof(cur)-1); cur[sizeof(cur)-1] = 0;
        hol = cmdb_is_holiday(nxt);
        if (hol < 0) { tpabort(0); return 1; }
        if (++guard > 30) break;
    } while (hol == 1);

    if (cmdb_set_param("BIZ_DATE", nxt) < 0) { tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> cm_bizday_roll_batch COMMIT: BIZ_DATE -> %s\n", nxt);

    tpclose(); tpterm();
    return 0;
}
