/*
 * py_seizescan_batch.pgc - py 압류계좌 지급 차단 스캔 배치 (UPDATE FROM, XA).
 *
 * 압류(SEIZED) 계좌로 향하는 당일 미지급(R/A) 건을 UPDATE ... FROM 조인
 * 한 방으로 '압류차단' 보류(H) 전이하고, 압류 계좌 수도 함께 리포트.
 * host 변수는 전용 카피북 py_seizescan_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: py_seizescan_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

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

    EXEC SQL INCLUDE py_seizescan_cpy;

    strncpy(c_bizdate, bizdate, sizeof(c_bizdate)-1); c_bizdate[sizeof(c_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 SELECT count(*) INTO :c_accts FROM py_account WHERE status = 'SEIZED';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "SELECT FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }

    EXEC SQL UPDATE py_payout SET status = 'H', reject_reason = '압류차단', updated_at = now()
        FROM py_account a
        WHERE py_payout.account_no = a.account_no
          AND py_payout.biz_date = :c_bizdate
          AND py_payout.status IN ('R','A')
          AND a.status = 'SEIZED';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "UPDATE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    c_blocked = sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> py_seizescan_batch COMMIT: bizdate=%s 압류계좌=%ld 차단보류=%ld건\n", bizdate, c_accts, c_blocked);

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