/*
 * mm_grade_dist_batch.pgc - 가맹점 등급 분포 배치 (커서 + upsert) (XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction, the EXEC SQL work runs on that branch, then tpcommit drives XA 2PC.
 * Usage: mm_grade_dist_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

int main(int argc, char **argv)
{
    long rows = 0; (void)rows; (void)argc; (void)argv;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_grade[8], h_date[16]; long h_cnt;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_date, (argc > 1) ? argv[1] : "2026-07-19", sizeof(h_date)-1); h_date[sizeof(h_date)-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 gdc CURSOR FOR
        SELECT grade, count(*) FROM mm_merchant_ext GROUP BY grade ORDER BY grade;
    EXEC SQL OPEN gdc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH gdc INTO :h_grade, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE gdc; tpabort(0); return 1; }
        EXEC SQL INSERT INTO mm_grade_dist (dist_date, grade, merch_cnt)
            VALUES (:h_date, :h_grade, :h_cnt)
            ON CONFLICT (dist_date, grade) DO UPDATE SET merch_cnt = EXCLUDED.merch_cnt;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE gdc; tpabort(0); return 1; }
        rows++;
    }
    EXEC SQL CLOSE gdc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "mm_grade_dist_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(">>> mm_grade_dist_batch COMMIT: date=%s 등급=%ld\n", h_date, rows);

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