/*
 * st_rebate_batch.pgc - 리베이트 정산 배치 (XA 배치).
 * 당일 가맹점 집계(st_merch_settle)를 커서로 순회하며 부과 수수료의 5%를 리베이트로
 * 산정해 정산 조정(st_adjust)에 양(+) 금액으로 적립한다.
 * 사용법: st_rebate_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_rebate_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_rebate_rec_t rec;
    memset(&rec, 0, sizeof(rec));
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_mid[64];
    long h_fee;
    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 rebate_bc CURSOR FOR
        SELECT merchant_id, fee_amount FROM st_merch_settle
        WHERE biz_date = :h_bizdate AND fee_amount > 0 ORDER BY merchant_id;
    EXEC SQL OPEN rebate_bc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        long rebate, adj;
        EXEC SQL FETCH rebate_bc INTO :h_mid, :h_fee;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE rebate_bc; tpabort(0); return 1; }
        rebate = h_fee * 500 / 10000;                /* 수수료 5% 리베이트 */
        if (rebate <= 0) continue;
        adj = stdb_insert_adjust(0, 0, rebate, "REBATE", bizdate);
        if (adj < 0) { EXEC SQL CLOSE rebate_bc; tpabort(0); return 1; }
        rec.merchants++; rec.rebate_total += rebate; rec.adj_last = adj;
        printf("    REBATE %-8s fee=%ld -> %ld (adj=%ld)\n", h_mid, h_fee, rebate, adj);
    }
    EXEC SQL CLOSE rebate_bc;

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