/*
 * st_whtdetail_batch.pgc - 원천세 명세 집계 배치 (XA 배치).
 * 당일 가맹점별 정률(PCT) 수수료 합계를 커서로 집계해 원천징수세(3.3%)를 산정하고
 * 명세로 출력한다 (집계/출력 전용, 원장 미기록).
 * 사용법: st_whtdetail_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "acq_common.h"
#include "st_whtdetail_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_whtdetail_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 whtdetail_bc CURSOR FOR
        SELECT merchant_id, coalesce(sum(amount),0) FROM st_settle_dtl
        WHERE biz_date = :h_bizdate AND fee_type = 'PCT'
        GROUP BY merchant_id ORDER BY merchant_id;
    EXEC SQL OPEN whtdetail_bc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        long wht;
        EXEC SQL FETCH whtdetail_bc INTO :h_mid, :h_fee;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE whtdetail_bc; tpabort(0); return 1; }
        wht = acq_wht_amt(h_fee, 330);               /* 3.3% 원천 */
        rec.merchants++; rec.fee_total += h_fee; rec.wht_total += wht;
        printf("    WHT %-8s fee=%ld wht=%ld\n", h_mid, h_fee, wht);
    }
    EXEC SQL CLOSE whtdetail_bc;

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