/*
 * st_instant_batch.pgc - 즉시정산 지급 배치 (XA 배치).
 * 당일 정산(settlement)을 가맹점별 net 으로 집계해 지급 원장(st_payment)에 즉시
 * 지급 완료(PAID) 건으로 등록한다 (SCHEDULED 단계 생략).
 * 사용법: st_instant_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_instant_batch.h"

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

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