/*
 * rc_reclass_batch.pgc - rc HOLD 대사 CASE 재분류 (집합 UPDATE + XA).
 *
 * 금액 구간에 따라 HOLD 대사를 CASE 로 EXCEPTION/RELEASED 로 재분류하는 단일 집합 UPDATE.
 * 사용법: rc_reclass_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"
#include "rc_reclass_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    rc_reclass_rec_t rec; rec.touched = 0;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-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 UPDATE rc_match_log
        SET status = CASE WHEN amount >= 1000000 THEN 'EXCEPTION' ELSE 'RELEASED' END,
            updated_at = now()
        WHERE biz_date = :h_bizdate AND status = 'HOLD';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "UPDATE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.touched = (long) sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: bizdate=%s reclassified=%ld\n", RC_RECLASS_TAG, bizdate, rec.touched);

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