/*
 * vl_logpurge_batch.pgc - vl 정상 검증로그 보존기간 삭제 배치 (XA 단일 글로벌 트랜잭션 배치).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction, EXEC SQL runs on the biz_date, then tpcommit drives XA 2PC.
 * Usage: vl_logpurge_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_logpurge_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    const char *cutoff = (argc > 2) ? argv[2] : VL_LOGPURGE_CUTOFF;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_cut[16];
    EXEC SQL END DECLARE SECTION;
    vl_logpurge_rec_t rec;
    (void) bizdate;

    strncpy(h_cut, cutoff, sizeof(h_cut)-1); h_cut[sizeof(h_cut)-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 DELETE FROM vl_check_log
        WHERE biz_date < :h_cut AND result_code = 0;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_logpurge_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.deleted = (long) sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> vl_logpurge_batch COMMIT: cutoff=%s 삭제=%ld\n", cutoff, rec.deleted);

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