/*
 * py_dormscan_batch.pgc - py 휴면 계좌 스캔 배치 (NOT EXISTS UPDATE, XA).
 *
 * 지정 기준일 이후 지급 이력이 전혀 없는 활성(ACTIVE) 계좌를 NOT EXISTS
 * 서브쿼리로 골라 휴면(DORMANT)으로 일괄 전환한다. ONE XA transaction.
 * Usage: py_dormscan_batch [SINCE-YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

int main(int argc, char **argv)
{
    const char *since = (argc > 1) ? argv[1] : "2026-04-01";
    long dormant;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_since[16];
    EXEC SQL END DECLARE SECTION;

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

    EXEC SQL UPDATE py_account SET status = 'DORMANT', updated_at = now()
        WHERE status = 'ACTIVE'
          AND NOT EXISTS (SELECT 1 FROM py_payout p
                          WHERE p.account_no = py_account.account_no AND p.biz_date >= :h_since);
    if (sqlca.sqlcode < 0) { fprintf(stderr, "UPD FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    dormant = sqlca.sqlerrd[2];

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