/*
 * py_acctsync_batch.pgc - py 지급계좌 잔액 정합 점검 배치 (커서 + REVIEW 마킹, XA).
 *
 * 잔액이 음수로 뒤집힌 지급계좌를 커서로 찾아 REVIEW 상태로 마킹해
 * 지급 경로에서 격리하고, 전체 최저 잔액도 리포트한다.
 * host 변수는 전용 카피북 py_acctsync_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: py_acctsync_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

int main(int argc, char **argv)
{
    long negatives = 0;

    EXEC SQL INCLUDE py_acctsync_cpy;

    (void)argc; (void)argv;

    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 pas CURSOR FOR
        SELECT account_no, merchant_id, balance FROM py_account
         WHERE balance < 0 ORDER BY balance;
    EXEC SQL OPEN pas;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH pas INTO :c_acct, :c_merch, :c_bal;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pas; tpabort(0); return 1; }
        negatives++;
        printf("  [음수잔액] %s (%s) balance=%ld -> REVIEW\n", c_acct, c_merch, c_bal);
    }
    EXEC SQL CLOSE pas;

    EXEC SQL UPDATE py_account SET status = 'REVIEW', updated_at = now()
        WHERE balance < 0 AND status <> 'REVIEW';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "UPDATE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    c_flagged = sqlca.sqlerrd[2];

    EXEC SQL SELECT coalesce(min(balance),0) INTO :c_minbal FROM py_account;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "SELECT FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> py_acctsync_batch COMMIT: 음수계좌=%ld REVIEW신규=%ld 최저잔액=%ld\n",
           negatives, c_flagged, c_minbal);

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