/*
 * cm_archive_batch.pgc - cm 정보(I) 로그 보관(A) 전이 배치 (XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; 해당 영업일 정보 로그 중 log_id 오름차순 앞 5000건을 보관(A)
 * 상태로 전이(UPDATE ... WHERE log_id IN (서브셀렉트 ORDER BY LIMIT)); tpcommit.
 * Usage: cm_archive_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "cm_dbio.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_upd = 0;
    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 cm_log SET log_level = 'A'
        WHERE log_id IN (SELECT log_id FROM cm_log
                         WHERE biz_date = :h_bizdate AND log_level = 'I'
                         ORDER BY log_id LIMIT 5000);
    if (sqlca.sqlcode < 0) { fprintf(stderr, "cm_archive_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    h_upd = sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> cm_archive_batch COMMIT: bizdate=%s archived=%ld\n", bizdate, h_upd);

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