/*
 * st_paysweep_batch.pgc - st 소액 예정지급 일괄 보류 (집합 UPDATE + XA).
 *
 * 최소액 미만 SCHEDULED 지급을 하나의 집합 UPDATE 로 HELD 전환. 사용법:
 * st_paysweep_batch [YYYY-MM-DD] [floor]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_paysweep_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_paysweep_rec_t rec;
    rec.floor_amt = (argc > 2) ? atol(argv[2]) : 10000;
    rec.held = 0;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_floor = rec.floor_amt;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 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; }

    EXEC SQL UPDATE st_payment SET status = 'HELD'
        WHERE biz_date = :h_bizdate AND status = 'SCHEDULED' AND net_amount < :h_floor;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "UPDATE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.held = (long) sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: bizdate=%s floor=%ld held=%ld\n", ST_PAYSWEEP_TAG, bizdate, rec.floor_amt, rec.held);

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