/*
 * mm_term_retire_batch.pgc - 비활성 단말 일괄 폐기 배치 (set-based UPDATE + XA).
 *
 * 개통 해지되어 INACTIVE로 남은 단말을 일괄 RETIRED로 확정한다. 활성/이미폐기 단말은
 * 건드리지 않는다. ONE global XA transaction. host 변수는 mm_term_retire_cpy.h.
 * Usage: mm_term_retire_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

int main(int argc, char **argv)
{
    (void)argc; (void)argv;
    EXEC SQL INCLUDE mm_term_retire_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 UPDATE mm_terminal SET status = 'RETIRED' WHERE status = 'INACTIVE';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "UPDATE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    b_retired = sqlca.sqlerrd[2];

    EXEC SQL SELECT count(*) INTO :b_remain FROM mm_terminal WHERE status = 'ACTIVE';
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_term_retire_batch COMMIT: 폐기=%ld 잔여활성=%ld\n", b_retired, b_remain);

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