/*
 * st_grpalloc_batch.pgc - 그룹 통합정산 배분 배치 (XA 배치).
 * 가맹점 ID 앞 2자리를 그룹 키로 묶어 당일 net 을 그룹별로 집계하고, 각 그룹의 대표
 * 지급처로 통합 지급 예정(st_payment)을 등록한다.
 * 사용법: st_grpalloc_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_grpalloc_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_grpalloc_rec_t rec;
    memset(&rec, 0, sizeof(rec));
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_grp[8];
    long 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 grpalloc_bc CURSOR FOR
        SELECT left(merchant_id, 2), coalesce(sum(net_amount),0) FROM st_merch_settle
        WHERE biz_date = :h_bizdate GROUP BY left(merchant_id, 2) ORDER BY 1;
    EXEC SQL OPEN grpalloc_bc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        long pay;
        EXEC SQL FETCH grpalloc_bc INTO :h_grp, :h_net;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE grpalloc_bc; tpabort(0); return 1; }
        if (h_net <= 0) continue;
        pay = stdb_insert_payment(h_grp, h_net, bizdate, "SCHEDULED", bizdate);
        if (pay < 0) { EXEC SQL CLOSE grpalloc_bc; tpabort(0); return 1; }
        rec.groups++; rec.alloc_total += h_net; rec.pay_last = pay;
        printf("    GRP %-4s net=%ld (pay=%ld)\n", h_grp, h_net, pay);
    }
    EXEC SQL CLOSE grpalloc_bc;

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