/*
 * rc_audit_batch.pgc - rc 미해결 예외 감사 -> 경보 생성 (커서 + XA).
 *
 * 당일 미해결 예외를 커서로 순회하며 각 건에 대해 rc_alert 에 WARN 경보를 남긴다.
 * 하나의 글로벌 트랜잭션에서 반복 INSERT 후 2PC 커밋. 사용법: rc_audit_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"
#include "rc_audit_batch.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_reason[64], h_msg[80];
    long h_pid;
    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 DECLARE adc CURSOR FOR
        SELECT purchase_id, reason FROM rc_exception
        WHERE biz_date = :h_bizdate AND resolved = false ORDER BY exc_id;
    EXEC SQL OPEN adc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH adc INTO :h_pid, :h_reason;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE adc; tpabort(0); return 1; }
        rec.pid = h_pid;
        strncpy(rec.reason, h_reason, sizeof(rec.reason)-1); rec.reason[sizeof(rec.reason)-1] = 0;
        snprintf(h_msg, sizeof(h_msg), "unresolved: %s", rec.reason);
        EXEC SQL INSERT INTO rc_alert (alert_id, purchase_id, lvl, message, biz_date)
            VALUES (nextval('rc_alert_seq'), :h_pid, 'WARN', :h_msg, :h_bizdate);
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE adc; tpabort(0); return 1; }
        alerts++;
    }
    EXEC SQL CLOSE adc;

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

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