/*
 * st_rankpay_batch.pgc - st 가맹점별 최상위 지급 -> 정산상세 적재 (윈도우 커서 + XA).
 *
 * row_number() OVER (PARTITION BY merchant_id ORDER BY net_amount DESC) 커서로 가맹점별
 * 1순위 지급을 골라 st_settle_dtl 에 RATE 라인으로 기록. 사용법: st_rankpay_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_rankpay_batch.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_mid[32];
    long h_net, h_rn;
    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 rpc CURSOR FOR
        SELECT merchant_id, net_amount,
               row_number() OVER (PARTITION BY merchant_id ORDER BY net_amount DESC)
        FROM st_payment WHERE biz_date = :h_bizdate;
    EXEC SQL OPEN rpc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH rpc INTO :h_mid, :h_net, :h_rn;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE rpc; tpabort(0); return 1; }
        strncpy(rec.merchant, h_mid, sizeof(rec.merchant)-1); rec.merchant[sizeof(rec.merchant)-1] = 0;
        rec.net = h_net; rec.rnk = h_rn;
        if (rec.rnk == 1) {
            EXEC SQL INSERT INTO st_settle_dtl (dtl_id, settlement_id, purchase_id, merchant_id, fee_type, amount, biz_date)
                VALUES (nextval('st_dtl_seq'), 0, 0, :h_mid, 'RATE', :h_net, :h_bizdate);
            if (sqlca.sqlcode < 0) { EXEC SQL CLOSE rpc; tpabort(0); return 1; }
            loaded++;
        }
    }
    EXEC SQL CLOSE rpc;

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

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