/*
 * lg_linepurge_batch.pgc - lg 마감 분개라인 정리 (기간 DELETE 배치, XA).
 *
 * Removes closed ledger lines older than a cutoff date with a single ranged
 * DELETE, inside ONE XA transaction.
 * Usage: lg_linepurge_batch BEFORE_DATE
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "lg_linepurge_batch.h"

int main(int argc, char **argv)
{
    const char *before = (argc > 1) ? argv[1] : "2026-01-01";
    lg_linepurge_rec_t rec;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_before[16];
    long h_removed;
    EXEC SQL END DECLARE SECTION;

    strncpy(h_before, before, sizeof(h_before)-1); h_before[sizeof(h_before)-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 lg_ledger_line
        WHERE status = 'closed' AND biz_date < :h_before;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "lg_linepurge_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    h_removed = sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }

    strncpy(rec.before, before, sizeof(rec.before)-1); rec.before[sizeof(rec.before)-1] = 0;
    rec.removed = h_removed;
    printf(">>> lg_linepurge_batch COMMIT: before=%s removed=%ld\n", rec.before, rec.removed);

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