/*
 * st_partial_batch.pgc - 부분정산 잔여 스윕 배치 (HAVING 커서 + XA).
 * 부분정산으로 인해 정산 합계가 매입 net 에 못 미치는 매입을 HAVING 커서로
 * 찾아, 잔여분을 PARTIAL 정산 레코드로 마저 생성한다. 사용법: st_partial_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_partial_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_partial_rec_t rec;
    memset(&rec, 0, sizeof(rec));
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_merch[64];
    long h_pid, h_remain;
    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 partial_bc CURSOR FOR
        SELECT p.purchase_id, p.merchant_id, p.net - sum(s.net)
        FROM purchase p JOIN settlement s ON s.purchase_id = p.purchase_id
        WHERE p.biz_date = :h_bizdate AND s.status <> 'CANCELLED'
        GROUP BY p.purchase_id, p.merchant_id, p.net
        HAVING sum(s.net) < p.net;
    EXEC SQL OPEN partial_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 partial_bc INTO :h_pid, :h_merch, :h_remain;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE partial_bc; tpabort(0); return 1; }
        if (h_remain <= 0) continue;
        EXEC SQL INSERT INTO settlement (settlement_id, purchase_id, merchant_id, net, biz_date, status)
            VALUES (nextval('settlement_seq'), :h_pid, :h_merch, :h_remain, :h_bizdate, 'PARTIAL');
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE partial_bc; tpabort(0); return 1; }
        rec.swept++;
        rec.swept_amt += h_remain;
    }
    EXEC SQL CLOSE partial_bc;

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

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