/*
 * st_whtreport_batch.pgc - 원천세 명세 배치 (가맹점별 커서 명세 출력 + XA).
 * 대상 월의 정산 상세(WHT)를 가맹점별 GROUP BY 커서로 순회하며 원천세 명세
 * 라인을 한 줄씩 출력하고 총액을 집계한다 (신고 명세서 생성, 조회 전용).
 * 사용법: st_whtreport_batch [YYYY-MM-DD (해당 월 기준일)]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_whtreport_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_whtreport_rec_t rec;
    memset(&rec, 0, sizeof(rec));
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_merch[64];
    long h_cnt, h_wht;
    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 whtrpt_bc CURSOR FOR
        SELECT merchant_id, count(*), coalesce(sum(amount),0) FROM st_settle_dtl
        WHERE fee_type = 'WHT'
          AND to_char(biz_date,'YYYY-MM') = to_char(:h_bizdate::date,'YYYY-MM')
        GROUP BY merchant_id ORDER BY merchant_id;
    EXEC SQL OPEN whtrpt_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 whtrpt_bc INTO :h_merch, :h_cnt, :h_wht;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE whtrpt_bc; tpabort(0); return 1; }
        printf("    WHT %-16s lines=%ld tax=%ld\n", h_merch, h_cnt, h_wht);
        rec.lines++;
        rec.wht_total += h_wht;
    }
    EXEC SQL CLOSE whtrpt_bc;

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

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