/*
 * vl_negbal_batch.pgc - 마이너스 잔액 가맹점 검출 배치 (XA 단일 글로벌 트랜잭션 배치).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; 커서로 일별 집계 순액이 음수인 가맹점을 훑어 의심거래로 적재하고
 * 최악치를 보고한 뒤 tpcommit drives XA 2PC.
 * Usage: vl_negbal_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_dbio.h"
#include "vl_negbal_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_merch[64];
    long h_net;
    EXEC SQL END DECLARE SECTION;
    char detail[96];
    vl_negbal_rec_t rec; rec.merchants = 0; rec.worst_amt = 0;

    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 vnbc CURSOR FOR
        SELECT merchant_id, net_amount FROM merchant_summary
        WHERE biz_date = :h_bizdate AND net_amount < 0
        ORDER BY net_amount;
    EXEC SQL OPEN vnbc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_negbal_batch OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH vnbc INTO :h_merch, :h_net;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "vl_negbal_batch FETCH FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
        if (rec.merchants == 0) rec.worst_amt = h_net;   /* 정렬상 첫 행이 최악치 */
        snprintf(detail, sizeof(detail), "가맹점 %s 순액 %ld", h_merch, h_net);
        if (vldb_insert_suspect(0, VL_NEGBAL_RULE, "CRIT", detail, h_bizdate) < 0) {
            fprintf(stderr, "vl_negbal_batch 의심거래 적재 FAIL\n"); tpabort(0); return 1;
        }
        rec.merchants++;
    }
    EXEC SQL CLOSE vnbc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> vl_negbal_batch COMMIT: bizdate=%s 음수잔액가맹점=%ld 최악=%ld\n",
           bizdate, rec.merchants, rec.worst_amt);

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