/*
 * cm_notidigest_batch.pgc - cm 알림 발송 일별 다이제스트 배치 (XA).
 *
 * 기준일 NOTI 발송 로그를 채널 접두([SMS>/[EMAIL>/[PUSH>)별로 나눠 집계하고,
 * 하루 한 건의 다이제스트를 cm_log (svc=NOTIDIG) 로 적재한다. 발송이 전혀
 * 없던 날도 zero 다이제스트를 남겨 결번을 알 수 있게 한다.
 * Usage: cm_notidigest_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "cm_notidigest_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    cm_notidigest_rec_t rec;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_msg[128];
    long h_sms = 0, h_mail = 0, h_push = 0, h_all = 0;
    EXEC SQL END DECLARE SECTION;

    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(*),
                    coalesce(sum(CASE WHEN msg LIKE '[SMS>%'   THEN 1 ELSE 0 END), 0),
                    coalesce(sum(CASE WHEN msg LIKE '[EMAIL>%' THEN 1 ELSE 0 END), 0),
                    coalesce(sum(CASE WHEN msg LIKE '[PUSH>%'  THEN 1 ELSE 0 END), 0)
        INTO :h_all, :h_sms, :h_mail, :h_push
        FROM cm_log WHERE svc_name = 'NOTI' AND biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }

    rec.total = h_all; rec.sms = h_sms; rec.email = h_mail; rec.push = h_push;
    snprintf(h_msg, sizeof(h_msg), "NOTIDIG total=%ld sms=%ld email=%ld push=%ld",
             rec.total, rec.sms, rec.email, rec.push);

    EXEC SQL INSERT INTO cm_log (log_id, svc_name, log_level, msg, biz_date)
        VALUES (nextval('cm_log_seq'), 'NOTIDIG', 'I', :h_msg, :h_bizdate);
    if (sqlca.sqlcode < 0) { fprintf(stderr, "cm_notidigest_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(">>> cm_notidigest_batch COMMIT: bizdate=%s 총=%ld (SMS=%ld EMAIL=%ld PUSH=%ld)\n",
           bizdate, rec.total, rec.sms, rec.email, rec.push);

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