/*
 * cl_relock_batch.pgc - cl 완료 기간 일괄 잠금 배치 (커서 + upsert + XA).
 *
 * status='C' 로 마감된 고유 period_key 를 커서로 훑어 cl_period_lock 에
 * upsert(ON CONFLICT) 하여 기간을 잠근다. 전 구간 ONE global XA transaction.
 * host 변수는 전용 카피북 cl_relock_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: cl_relock_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

int main(int argc, char **argv)
{
    long locked = 0;
    (void) argc; (void) argv;

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

    EXEC SQL DECLARE crel CURSOR FOR
        SELECT DISTINCT period_key FROM cl_close_log WHERE status = 'C'
        ORDER BY period_key;
    EXEC SQL OPEN crel;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH crel INTO :r_period;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE crel; tpabort(0); return 1; }
        EXEC SQL INSERT INTO cl_period_lock (period_key, locked) VALUES (:r_period, true)
            ON CONFLICT (period_key) DO UPDATE SET locked = true, locked_at = now();
        if (sqlca.sqlcode < 0) { fprintf(stderr, "UPSERT FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE crel; tpabort(0); return 1; }
        locked++;
    }
    EXEC SQL CLOSE crel;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> cl_relock_batch COMMIT: 잠금기간=%ld\n", locked);

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