/*
 * mm_stat_batch.pgc - 등급별 가맹점 수 통계 배치 (커서 + XA).
 *
 * Cursors over mm_merchant_ext grouped by grade, upserting a per-grade count
 * into mm_grade_stat for the run date, all under ONE global XA transaction.
 * Usage: mm_stat_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_statdate[16], h_grade[8];
    long h_cnt;
    EXEC SQL END DECLARE SECTION;

    strncpy(h_statdate, statdate, sizeof(h_statdate)-1); h_statdate[sizeof(h_statdate)-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 gsc CURSOR FOR
        SELECT grade, count(*) FROM mm_merchant_ext
        WHERE status = 'ACTIVE' GROUP BY grade ORDER BY grade;
    EXEC SQL OPEN gsc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH gsc INTO :h_grade, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE gsc; tpabort(0); return 1; }
        EXEC SQL INSERT INTO mm_grade_stat (stat_date, grade, merch_cnt)
            VALUES (:h_statdate, :h_grade, :h_cnt)
            ON CONFLICT (stat_date, grade) DO UPDATE
            SET merch_cnt = EXCLUDED.merch_cnt, updated_at = now();
        if (sqlca.sqlcode < 0) { fprintf(stderr, "UPSERT FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE gsc; tpabort(0); return 1; }
        rows++;
    }
    EXEC SQL CLOSE gsc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_stat_batch COMMIT: statdate=%s 등급구간=%ld\n", statdate, rows);

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