/*
 * py_cancelpurge_batch.pgc - py 취소 지급 정리 (기간 DELETE 배치, XA).
 *
 * Deletes cancelled(C) payouts across a [from,to] date range in ONE XA
 * transaction and reports how many rows were purged.
 * Usage: py_cancelpurge_batch FROM_DATE TO_DATE
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "py_cancelpurge_batch.h"

int main(int argc, char **argv)
{
    const char *from_date = (argc > 1) ? argv[1] : "2026-01-01";
    const char *to_date   = (argc > 2) ? argv[2] : "2026-06-30";
    py_cancelpurge_rec_t rec;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_from[16], h_to[16];
    long h_purged;
    EXEC SQL END DECLARE SECTION;

    strncpy(h_from, from_date, sizeof(h_from)-1); h_from[sizeof(h_from)-1] = 0;
    strncpy(h_to, 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 py_payout
        WHERE status = 'C' AND biz_date >= :h_from AND biz_date <= :h_to;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "py_cancelpurge_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    h_purged = sqlca.sqlerrd[2];

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

    strncpy(rec.from_date, from_date, sizeof(rec.from_date)-1); rec.from_date[sizeof(rec.from_date)-1] = 0;
    strncpy(rec.to_date, to_date, sizeof(rec.to_date)-1); rec.to_date[sizeof(rec.to_date)-1] = 0;
    rec.purged = h_purged;
    printf(">>> py_cancelpurge_batch COMMIT: range=%s..%s purged=%ld\n", rec.from_date, rec.to_date, rec.purged);

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