/*
 * st_grproll_batch.pgc - 가맹점그룹 통합정산 롤업 배치 (prefix 그룹 커서 + upsert + XA).
 * 가맹점 ID 앞 2자리를 그룹키로 삼아 당일 정산을 그룹 단위로 롤업 집계하고,
 * 그룹키 행을 st_merch_settle 에 upsert 한다 (그룹 통합정산 기초).
 * 사용법: st_grproll_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_grproll_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_grproll_rec_t rec;
    memset(&rec, 0, sizeof(rec));
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_grp[8];
    long h_cnt, h_net;
    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 grproll_bc CURSOR FOR
        SELECT substr(merchant_id, 1, 2), count(*), coalesce(sum(net),0)
        FROM settlement WHERE biz_date = :h_bizdate
        GROUP BY substr(merchant_id, 1, 2) ORDER BY 1;
    EXEC SQL OPEN grproll_bc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH grproll_bc INTO :h_grp, :h_cnt, :h_net;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE grproll_bc; tpabort(0); return 1; }
        {
            char grpkey[16];
            snprintf(grpkey, sizeof(grpkey), "GRP:%s", h_grp);
            if (stdb_upsert_merch_settle(grpkey, bizdate, h_net, 0, h_net, h_cnt) < 0) { EXEC SQL CLOSE grproll_bc; tpabort(0); return 1; }
            rec.groups++;
            rec.rolled_net += h_net;
        }
    }
    EXEC SQL CLOSE grproll_bc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: bizdate=%s groups=%ld rolled_net=%ld\n", ST_GRPROLL_TAG, bizdate, rec.groups, rec.rolled_net);

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