/*
 * py_mergesmall_batch.pgc - py 분할건 합산 정리 배치 (HAVING 커서 + 재생성, XA).
 *
 * 당일 요청(R) SPLIT 건이 2건 이상인 가맹점을 커서로 뽑아 가맹점마다
 * 원건들을 취소(C) 표시하고 합산 1건(BULK)으로 재생성한다 (이체 건수 절감).
 * host 변수는 전용 카피북 py_mergesmall_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: py_mergesmall_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

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

    EXEC SQL INCLUDE py_mergesmall_cpy;

    strncpy(c_bizdate, bizdate, sizeof(c_bizdate)-1); c_bizdate[sizeof(c_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(120, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL DECLARE pms CURSOR FOR
        SELECT merchant_id, count(*), coalesce(sum(amount),0), coalesce(sum(fee),0),
               coalesce(sum(net),0), coalesce(min(account_no),'')
          FROM py_payout
         WHERE biz_date = :c_bizdate AND status = 'R' AND channel = 'SPLIT'
         GROUP BY merchant_id HAVING count(*) >= 2
         ORDER BY merchant_id;
    EXEC SQL OPEN pms;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH pms INTO :c_merch, :c_cnt, :c_amt, :c_fee, :c_net, :c_acct;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pms; tpabort(0); return 1; }
        EXEC SQL UPDATE py_payout SET status = 'C', reject_reason = '분할합산', updated_at = now()
            WHERE merchant_id = :c_merch AND biz_date = :c_bizdate
              AND status = 'R' AND channel = 'SPLIT';
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pms; tpabort(0); return 1; }
        EXEC SQL SELECT nextval('py_payout_seq') INTO :c_newid;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pms; tpabort(0); return 1; }
        EXEC SQL INSERT INTO py_payout (payout_id, merchant_id, account_no, amount, fee, net,
                                        status, channel, biz_date)
            VALUES (:c_newid, :c_merch, :c_acct, :c_amt, :c_fee, :c_net, 'R', 'BULK', :c_bizdate);
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pms; tpabort(0); return 1; }
        merchants++; merged += c_cnt;
        printf("  [분할합산] %s: %ld건 -> BULK id=%ld (net=%ld)\n", c_merch, c_cnt, c_newid, c_net);
    }
    EXEC SQL CLOSE pms;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> py_mergesmall_batch COMMIT: bizdate=%s 가맹점=%ld 통합원건=%ld\n", bizdate, merchants, merged);

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