/*
 * mm_rel_count_batch.pgc - 대표 가맹점별 하위 수 집계 배치 (커서 + XA).
 *
 * MERCH_REL 활성 관계를 대표(code_name) 기준으로 집계하여 각 대표 가맹점에
 * REL_CNT 이력을 남긴다(하위 규모 스냅샷). ONE global XA transaction.
 * host 변수는 mm_rel_count_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_rel_count_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mm_dbio.h"

int main(int argc, char **argv)
{
    (void)argc; (void)argv;
    EXEC SQL INCLUDE mm_rel_count_cpy;
    b_groups = 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 rct CURSOR FOR
        SELECT code_name, count(*) FROM mm_code
        WHERE code_group = 'MERCH_REL' AND status = 'ACTIVE'
        GROUP BY code_name ORDER BY code_name;
    EXEC SQL OPEN rct;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH rct INTO :b_parent, :b_children;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE rct; tpabort(0); return 1; }
        snprintf(b_memo, sizeof(b_memo), "하위 %ld개", b_children);
        if (mmdb_insert_merch_hist(b_parent, "REL_CNT", "", b_memo, "하위 규모 집계") < 0) {
            EXEC SQL CLOSE rct; tpabort(0); return 1;
        }
        b_groups++;
    }
    EXEC SQL CLOSE rct;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_rel_count_batch COMMIT: 대표 %ld개 집계\n", b_groups);

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