/*
 * rc_purgeold_batch.pgc - rc 컷오프 이전 경보 일괄 삭제 (범위 DELETE + XA).
 *
 * 단일 범위 DELETE 를 하나의 글로벌 트랜잭션에서 수행하고 2PC 로 커밋.
 * 사용법: rc_purgeold_batch [YYYY-MM-DD(컷오프)]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"
#include "rc_purgeold_batch.h"

int main(int argc, char **argv)
{
    rc_purgeold_rec_t rec;
    strncpy(rec.cutoff, (argc > 1) ? argv[1] : "2026-07-01", sizeof(rec.cutoff)-1);
    rec.cutoff[sizeof(rec.cutoff)-1] = 0;
    rec.removed = 0;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_cut[16];
    EXEC SQL END DECLARE SECTION;
    strncpy(h_cut, rec.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 rc_alert WHERE biz_date < :h_cut AND lvl = 'INFO';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "DELETE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.removed = (long) sqlca.sqlerrd[2];

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

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