/*
 * mg_stat_batch.pgc - mg 채널 일통계 배치 (커서 + XA).
 *
 * Cursors over mg_msg_log aggregated per channel for a biz_date and upserts
 * mg_stat (수신/송신/오류 건수 + 금액합), all under ONE global XA transaction.
 * Usage: mg_stat_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mg_dbio.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long rows = 0;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    char h_chan[16];
    long h_in, h_out, h_err, h_sum;
    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 DECLARE msc CURSOR FOR
        SELECT channel,
               coalesce(sum(CASE WHEN direction='IN' THEN 1 ELSE 0 END),0),
               coalesce(sum(CASE WHEN direction='OUT' THEN 1 ELSE 0 END),0),
               coalesce(sum(CASE WHEN rc<>'00' THEN 1 ELSE 0 END),0),
               coalesce(sum(amount),0)
        FROM mg_msg_log WHERE biz_date = :h_bizdate
        GROUP BY channel ORDER BY channel;
    EXEC SQL OPEN msc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH msc INTO :h_chan, :h_in, :h_out, :h_err, :h_sum;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE msc; tpabort(0); return 1; }
        EXEC SQL INSERT INTO mg_stat (channel, biz_date, in_cnt, out_cnt, err_cnt, amount_sum)
            VALUES (:h_chan, :h_bizdate, :h_in, :h_out, :h_err, :h_sum)
            ON CONFLICT (channel, biz_date) DO UPDATE
            SET in_cnt = EXCLUDED.in_cnt, out_cnt = EXCLUDED.out_cnt,
                err_cnt = EXCLUDED.err_cnt, amount_sum = EXCLUDED.amount_sum,
                updated_at = now();
        if (sqlca.sqlcode < 0) { fprintf(stderr, "UPSERT FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE msc; tpabort(0); return 1; }
        rows++;
    }
    EXEC SQL CLOSE msc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mg_stat_batch COMMIT: bizdate=%s channels=%ld\n", bizdate, rows);

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