/*
 * au_fraudpurge_batch.pgc - au 저점수 부정로그 정리 배치 (복합조건 DELETE + XA).
 *
 * ATMI client: one global transaction; a range DELETE removes fraud-log rows that
 * are both older than the cutoff and below the score floor. Deleted count comes
 * from sqlca.sqlerrd[2]. Usage: au_fraudpurge_batch [cutoff] [min_score]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_fraudpurge_batch.h"

/* 최소 점수 하한 (음수 방지). */
long aub_fpurge_floor(long score)
{
    return (score < 0) ? 0 : score;
}

int main(int argc, char **argv)
{
    au_fpurge_ctx_t ctx;
    const char *cutoff = (argc > 1) ? argv[1] : "2026-07-01";
    long min_score = (argc > 2) ? atol(argv[2]) : 50;

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

    memset(&ctx, 0, sizeof(ctx));
    strncpy(ctx.cutoff, cutoff, sizeof(ctx.cutoff)-1);
    ctx.min_score = aub_fpurge_floor(min_score);
    strncpy(h_cut, ctx.cutoff, sizeof(h_cut)-1); h_cut[sizeof(h_cut)-1] = 0;
    h_min = ctx.min_score;

    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 au_fraud_log WHERE biz_date < :h_cut AND score < :h_min;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "au_fraudpurge_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(">>> au_fraudpurge_batch COMMIT: cutoff=%s min_score=%ld deleted=%ld\n",
           ctx.cutoff, ctx.min_score, ctx.deleted);

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