/*
 * st_vatdetail_batch.pgc - 부가세 명세 생성 배치 (XA 배치).
 * 당일 가맹점별 수수료 상세(MDR/VAN/RELAY) 합계를 커서로 집계해 공급가액으로 보고
 * 부가세(10%)를 산정, 정산 상세(st_settle_dtl)에 VAT 라인으로 기록한다.
 * 사용법: st_vatdetail_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_vatdetail_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_vatdetail_rec_t rec;
    memset(&rec, 0, sizeof(rec));
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_mid[64];
    long h_supply;
    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 vatdetail_bc CURSOR FOR
        SELECT merchant_id, coalesce(sum(amount),0) FROM st_settle_dtl
        WHERE biz_date = :h_bizdate AND fee_type IN ('MDR', 'VAN', 'RELAY')
        GROUP BY merchant_id ORDER BY merchant_id;
    EXEC SQL OPEN vatdetail_bc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }
    for (;;) {
        long vat, dtl;
        EXEC SQL FETCH vatdetail_bc INTO :h_mid, :h_supply;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE vatdetail_bc; tpabort(0); return 1; }
        vat = acq_vat(h_supply);
        dtl = stdb_insert_fee_dtl(0, 0, h_mid, "VAT", vat, bizdate);
        if (dtl < 0) { EXEC SQL CLOSE vatdetail_bc; tpabort(0); return 1; }
        rec.merchants++; rec.supply_total += h_supply; rec.vat_total += vat;
        printf("    VAT %-8s supply=%ld vat=%ld\n", h_mid, h_supply, vat);
    }
    EXEC SQL CLOSE vatdetail_bc;

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