/*
 * py_dormantstop_batch.pgc - py 휴면 가맹점 지급정지 배치 (NOT EXISTS 커서, XA).
 *
 * 최근 N일 지급 이력이 없는 정상 가맹점을 NOT EXISTS 커서로 뽑아, 가맹점별로
 * 지급계좌를 DORMANT 로 내리고 잔여 요청(R)건을 '휴면정지' 보류시킨다.
 * host 변수는 전용 카피북 py_dormantstop_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: py_dormantstop_batch [DAYS]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

int main(int argc, char **argv)
{
    long stopped = 0, total_accts = 0, total_held = 0;

    EXEC SQL INCLUDE py_dormantstop_cpy;

    c_days = (argc > 1) ? atol(argv[1]) : 30;
    if (c_days <= 0) c_days = 30;

    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 pds CURSOR FOR
        SELECT m.merchant_id FROM merchant m
         WHERE m.status = 'ACTIVE'
           AND NOT EXISTS (SELECT 1 FROM py_payout p
                            WHERE p.merchant_id = m.merchant_id
                              AND p.created_at > now() - :c_days * interval '1 day')
         ORDER BY m.merchant_id;
    EXEC SQL OPEN pds;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH pds INTO :c_merch;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pds; tpabort(0); return 1; }
        EXEC SQL UPDATE py_account SET status = 'DORMANT', updated_at = now()
            WHERE merchant_id = :c_merch AND status = 'ACTIVE';
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pds; tpabort(0); return 1; }
        c_accts = sqlca.sqlerrd[2];
        EXEC SQL UPDATE py_payout SET status = 'H', reject_reason = '휴면정지', updated_at = now()
            WHERE merchant_id = :c_merch AND status = 'R';
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pds; tpabort(0); return 1; }
        c_held = sqlca.sqlerrd[2];
        stopped++; total_accts += c_accts; total_held += c_held;
        printf("  [휴면정지] %s: 계좌 %ld개 정지, 지급 %ld건 보류\n", c_merch, c_accts, c_held);
    }
    EXEC SQL CLOSE pds;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> py_dormantstop_batch COMMIT: %ld일 기준 휴면=%ld곳 계좌=%ld 보류=%ld\n",
           c_days, stopped, total_accts, total_held);

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