/*
 * ac_unmatchpurge_batch.pgc - ac 미매입 로그 정리 배치 (구간 DELETE + XA).
 *
 * ATMI client: one global transaction; a range DELETE removes ac_unmatch rows
 * older than the cutoff. The deleted count comes from sqlca.sqlerrd[2].
 * tpcommit drives XA 2PC. Usage: ac_unmatchpurge_batch [cutoff-YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "ac_unmatchpurge_batch.h"

/* 배치 인자를 cutoff 문자열로 복사 (그대로 사용). */
void acb_purge_cutoff(const char *bizdate, char *out, int outsz)
{
    strncpy(out, bizdate, outsz - 1);
    out[outsz - 1] = 0;
}

int main(int argc, char **argv)
{
    ac_purge_ctx_t ctx;
    const char *cutoff = (argc > 1) ? argv[1] : "2026-07-01";

    EXEC SQL BEGIN DECLARE SECTION;
    char h_cut[16];
    long h_deleted = 0;
    EXEC SQL END DECLARE SECTION;

    memset(&ctx, 0, sizeof(ctx));
    acb_purge_cutoff(cutoff, ctx.cutoff, (int)sizeof(ctx.cutoff));
    strncpy(h_cut, ctx.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 ac_unmatch WHERE biz_date < :h_cut;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "ac_unmatchpurge_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    h_deleted = sqlca.sqlerrd[2];

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

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