/*
 * py_garnish_batch.pgc - py 압류/가압류 계좌 지급보류 배치 (커서 + UPDATE, XA).
 *
 * 압류(SEIZED)/가압류(GARNISH) 상태 계좌를 커서로 훑어 각 계좌의 미지급(R/A)
 * 건을 '압류보류'로 보류(H) 전이한다. 계좌별 보류 건수를 리포트한다.
 * host 변수는 전용 카피북 py_garnish_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: py_garnish_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

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

    EXEC SQL INCLUDE py_garnish_cpy;

    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(120, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL DECLARE pgr CURSOR FOR
        SELECT account_no FROM py_account WHERE status IN ('SEIZED','GARNISH') ORDER BY account_no;
    EXEC SQL OPEN pgr;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH pgr INTO :c_acct;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pgr; tpabort(0); return 1; }
        EXEC SQL UPDATE py_payout SET status = 'H', reject_reason = '압류보류', updated_at = now()
            WHERE account_no = :c_acct AND status IN ('R','A');
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pgr; tpabort(0); return 1; }
        c_held = sqlca.sqlerrd[2];
        accts++; held += c_held;
        if (c_held > 0) printf("  계좌 %s: %ld건 압류보류\n", c_acct, c_held);
    }
    EXEC SQL CLOSE pgr;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> py_garnish_batch COMMIT: accounts=%ld held=%ld\n", accts, held);
    tpclose(); tpterm();
    return 0;
}
