/*
 * mm_issuer_stat_batch.pgc - 국가별 발급사 통계 배치 (커서) (XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction, the EXEC SQL work runs on that branch, then tpcommit drives XA 2PC.
 * Usage: mm_issuer_stat_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_country[8]; long h_cnt;
    EXEC SQL END DECLARE SECTION;

    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 isc CURSOR FOR
        SELECT country, count(*) FROM mm_issuer WHERE status = 'ACTIVE'
        GROUP BY country ORDER BY country;
    EXEC SQL OPEN isc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH isc INTO :h_country, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE isc; tpabort(0); return 1; }
        rows++;
    }
    EXEC SQL CLOSE isc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "mm_issuer_stat_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_issuer_stat_batch COMMIT: 국가구간=%ld\n", rows);

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