/*
 * rc_threshold_batch.pgc - 임계초과 재대사 배치 (XA).
 * |차이금액| 이 임계값을 넘는 당일 차이 건들을 INSERT..SELECT 로 RERUN/HOLD
 * 재대사 큐에 일괄 등록하고, 등록이 있으면 CRIT 경보를 남긴다.
 * 사용법: rc_threshold_batch [YYYY-MM-DD] [LIMIT]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"
#include "rc_threshold_batch.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_msg[96];
    long h_limit;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    rec.limit = (argc > 2) ? atol(argv[2]) : RC_THRESHOLD_DEFAULT_LIMIT;
    h_limit = rec.limit;

    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 INSERT INTO rc_match_log (match_id, purchase_id, match_type, amount, status, biz_date)
        SELECT nextval('rc_match_seq'), purchase_id, 'RERUN', diff_amt, 'HOLD', biz_date
        FROM rc_diff
        WHERE biz_date = :h_bizdate AND abs(diff_amt) > :h_limit;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "%s INSERT FAIL [%d] %s\n", RC_THRESHOLD_TAG, sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.queued = sqlca.sqlerrd[2];

    if (rec.queued > 0) {
        snprintf(h_msg, sizeof(h_msg), "threshold %ld exceeded: rerun queued=%ld",
                 rec.limit, rec.queued);
        EXEC SQL INSERT INTO rc_alert (alert_id, purchase_id, lvl, message, biz_date)
            VALUES (nextval('rc_alert_seq'), 0, 'CRIT', :h_msg, :h_bizdate);
        if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    }

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

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