/*
 * mm_dormant_batch.pgc - 휴면 가맹점 탐지 배치 (N일 미갱신) (XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction, the EXEC SQL work runs on that branch, then tpcommit drives XA 2PC.
 * Usage: mm_dormant_batch [DAYS]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

int main(int argc, char **argv)
{
    long rows = 0; (void)rows; (void)argc; (void)argv;

    EXEC SQL BEGIN DECLARE SECTION;
    long h_cnt, h_days = (argc > 1) ? atol(argv[1]) : 180;
    EXEC SQL END DECLARE SECTION;

    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 SELECT count(*) INTO :h_cnt FROM mm_merchant_ext
        WHERE status = 'ACTIVE' AND updated_at < now() - (:h_days || ' days')::interval;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "mm_dormant_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_dormant_batch COMMIT: days=%ld 휴면=%ld\n", h_days, h_cnt);

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