/*
 * st_purgeadj_batch.pgc - st 무효 조정 범위 정리 (BETWEEN DELETE + XA).
 *
 * 두 영업일 사이의 delta=0 조정을 하나의 범위 DELETE 로 제거하고 2PC 커밋.
 * 사용법: st_purgeadj_batch [FROM] [TO]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_purgeadj_batch.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_from[16], h_to[16];
    EXEC SQL END DECLARE SECTION;
    strncpy(h_from, rec.from_date, sizeof(h_from)-1); h_from[sizeof(h_from)-1] = 0;
    strncpy(h_to, rec.to_date, sizeof(h_to)-1); h_to[sizeof(h_to)-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 st_adjust WHERE biz_date BETWEEN :h_from AND :h_to AND delta = 0;
    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: from=%s to=%s removed=%ld\n", ST_PURGEADJ_TAG, rec.from_date, rec.to_date, rec.removed);

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