/*
 * mg_healthz_batch.pgc - mg 게이트웨이 종합 헬스 스냅 배치 (다중 집계 + XA).
 *
 * UP 채널 수, 대기(Q) 큐 적체, 당일 오류(rc<>'00') 전문 수를 각각 집계해 한 스냅으로
 * 모아, UP 채널이 있고 적체가 임계 미만이면 healthy=1 로 판정한다 (헬스체크 세분).
 * Usage: mg_healthz_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mg_healthz_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    const long backlog_limit = 1000;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_up, h_backlog, h_err;
    EXEC SQL END DECLARE SECTION;
    mg_healthz_rec_t rec;
    memset(&rec, 0, sizeof(rec));

    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 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 SELECT count(*) INTO :h_up FROM mg_channel WHERE status = 'UP';
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    EXEC SQL SELECT count(*) INTO :h_backlog
        FROM mg_queue WHERE status = 'Q' AND biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    EXEC SQL SELECT count(*) INTO :h_err
        FROM mg_msg_log WHERE biz_date = :h_bizdate AND rc <> '00';
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }

    rec.chan_up = h_up;
    rec.queue_backlog = h_backlog;
    rec.err_today = h_err;
    rec.healthy = (h_up > 0 && h_backlog < backlog_limit) ? 1 : 0;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mg_healthz_batch COMMIT: bizdate=%s UP채널=%ld 큐적체=%ld 오류전문=%ld 건강=%s\n",
           bizdate, rec.chan_up, rec.queue_backlog, rec.err_today,
           rec.healthy ? "YES" : "NO");

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