/*
 * cl_reweigh_batch.pgc - cl 마감 총액 스냅샷 재계산 배치 (커서 + UPDATE + XA).
 *
 * period_key 프리픽스 마감을 커서로 훑어, 각 마감의 스냅샷 net 합을 다시 계산하여
 * cl_close_log.total_amount 를 갱신한다. 전 구간 ONE global XA transaction.
 * host 변수는 전용 카피북 cl_reweigh_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: cl_reweigh_batch [YYYY-MM]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

int main(int argc, char **argv)
{
    const char *prefix = (argc > 1) ? argv[1] : "2026-07";
    long updated = 0;

    EXEC SQL INCLUDE cl_reweigh_cpy;

    strncpy(w_prefix, prefix, sizeof(w_prefix)-1); w_prefix[sizeof(w_prefix)-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 DECLARE crw CURSOR FOR
        SELECT close_id FROM cl_close_log
        WHERE period_key LIKE :w_prefix || '%' AND status <> 'X'
        ORDER BY close_id;
    EXEC SQL OPEN crw;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH crw INTO :w_cid;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE crw; tpabort(0); return 1; }
        EXEC SQL SELECT coalesce(sum(net_amount),0) INTO :w_sum FROM cl_snapshot WHERE close_id = :w_cid;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE crw; tpabort(0); return 1; }
        EXEC SQL UPDATE cl_close_log SET total_amount = :w_sum, updated_at = now() WHERE close_id = :w_cid;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "UPDATE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE crw; tpabort(0); return 1; }
        updated++;
    }
    EXEC SQL CLOSE crw;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> cl_reweigh_batch COMMIT: prefix=%s 재계산=%ld건\n", prefix, updated);

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