/*
 * rc_notify_batch.pgc - 가맹점별 대사 결과 통보 배치 (커서 + XA).
 * 당일 가맹점 일별 집계(merchant_summary)를 커서로 순회하며 가맹점마다
 * 건수/정산액을 담은 INFO 통보 경보를 발송(적재)한다.
 * 사용법: rc_notify_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"
#include "rc_notify_batch.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_mid[64], h_msg[120];
    long h_cnt, h_net;
    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 cnb CURSOR FOR
        SELECT merchant_id, txn_count, net_amount FROM merchant_summary
        WHERE biz_date = :h_bizdate ORDER BY merchant_id;
    EXEC SQL OPEN cnb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH cnb INTO :h_mid, :h_cnt, :h_net;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE cnb; tpabort(0); return 1; }
        strncpy(rec.mid, h_mid, sizeof(rec.mid)-1); rec.mid[sizeof(rec.mid)-1] = 0;
        rec.txn_count = h_cnt; rec.net_amount = h_net;
        snprintf(h_msg, sizeof(h_msg), "recon notice %.32s: cnt=%ld net=%ld",
                 rec.mid, rec.txn_count, rec.net_amount);
        EXEC SQL INSERT INTO rc_alert (alert_id, purchase_id, lvl, message, biz_date)
            VALUES (nextval('rc_alert_seq'), 0, 'INFO', :h_msg, :h_bizdate);
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cnb; tpabort(0); return 1; }
        sent++;
    }
    EXEC SQL CLOSE cnb;

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

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