/*
 * mg_routechk_batch.pgc - mg 라우팅 룰 감사 배치 (커서 + XA).
 *
 * 전 라우팅 룰을 채널+MTI 순으로 커서 훑으며 비활성 룰 수를 세고, 직전 키와 같은
 * (채널,MTI) 활성 룰이 연달아 나오면 중복 라우팅으로 집계한다 (라우팅 룰 관리 감사).
 * Usage: mg_routechk_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mg_routechk_batch.h"

int main(int argc, char **argv)
{
    (void)argc; (void)argv;
    char prevkey[32] = "", curkey[32];
    EXEC SQL BEGIN DECLARE SECTION;
    char h_chan[16], h_mti[8];
    int  h_active;
    EXEC SQL END DECLARE SECTION;
    mg_routechk_rec_t rec;
    memset(&rec, 0, sizeof(rec));

    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 rkc CURSOR FOR
        SELECT channel, mti, active FROM mg_route ORDER BY channel, mti, route_id;
    EXEC SQL OPEN rkc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH rkc INTO :h_chan, :h_mti, :h_active;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE rkc; tpabort(0); return 1; }
        rec.rules++;
        if (!h_active) { rec.inactive++; continue; }
        snprintf(curkey, sizeof(curkey), "%s|%s", h_chan, h_mti);
        if (strcmp(curkey, prevkey) == 0) rec.dup_keys++;   /* 같은 키 활성 룰 중복 */
        strcpy(prevkey, curkey);
    }
    EXEC SQL CLOSE rkc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mg_routechk_batch COMMIT: 룰수=%ld 비활성=%ld 중복키=%ld\n",
           rec.rules, rec.inactive, rec.dup_keys);

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