/*
 * st_incent_batch.pgc - 구간별 인센티브 정산 배치 (커서 + 3단 요율 사다리 + XA).
 * 가맹점 일 집계(gross) 를 내림차순 커서로 순회, 1억/5천만/1천만 구간별
 * 인센티브(30/20/10bps)를 산정해 양수 조정으로 지급한다. 사용법: st_incent_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_incent_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_incent_rec_t rec;
    memset(&rec, 0, sizeof(rec));
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_merch[64];
    long h_gross;
    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 incent_bc CURSOR FOR
        SELECT merchant_id, gross_amount FROM st_merch_settle
        WHERE biz_date = :h_bizdate AND gross_amount >= 10000000
        ORDER BY gross_amount DESC;
    EXEC SQL OPEN incent_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 incent_bc INTO :h_merch, :h_gross;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE incent_bc; tpabort(0); return 1; }
        {
            long bps;
            if (h_gross >= 100000000)     { bps = 30; rec.tier1++; }
            else if (h_gross >= 50000000) { bps = 20; rec.tier2++; }
            else                          { bps = 10; rec.tier3++; }
            {
                long inc = h_gross * bps / 10000;
                if (stdb_insert_adjust(0, 0, inc, "INCENTIVE", bizdate) < 0) { EXEC SQL CLOSE incent_bc; tpabort(0); return 1; }
                rec.paid_sum += inc;
            }
        }
    }
    EXEC SQL CLOSE incent_bc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: bizdate=%s t1=%ld t2=%ld t3=%ld incentive_sum=%ld\n",
           ST_INCENT_TAG, bizdate, rec.tier1, rec.tier2, rec.tier3, rec.paid_sum);

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