/*
 * st_vatreport_batch.pgc - 부가세 신고자료 생성 배치 (월 집계 + 원장 마커 + XA).
 * 대상 월의 정산 상세 VAT 합계와 세금계산서 공급가/세액/건수를 집계·대사해
 * 신고 기초자료를 출력하고, VATRPT 원장 마커를 남긴다.
 * 사용법: st_vatreport_batch [YYYY-MM-DD (해당 월 기준일)]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_vatreport_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_vatreport_rec_t rec;
    memset(&rec, 0, sizeof(rec));
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_dtlvat, h_cnt, h_supply, h_invvat;
    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 SELECT coalesce(sum(amount),0) INTO :h_dtlvat FROM st_settle_dtl
        WHERE fee_type = 'VAT'
          AND to_char(biz_date,'YYYY-MM') = to_char(:h_bizdate::date,'YYYY-MM');
    if (sqlca.sqlcode < 0) { fprintf(stderr, "DTLVAT FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.dtl_vat = h_dtlvat;

    EXEC SQL SELECT count(*), coalesce(sum(supply),0), coalesce(sum(vat),0)
        INTO :h_cnt, :h_supply, :h_invvat FROM ac_tax_invoice
        WHERE to_char(biz_date,'YYYY-MM') = to_char(:h_bizdate::date,'YYYY-MM');
    if (sqlca.sqlcode < 0) { fprintf(stderr, "INV FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.inv_cnt = h_cnt; rec.inv_supply = h_supply; rec.inv_vat = h_invvat;

    EXEC SQL INSERT INTO ledger (ledger_id, purchase_id, entry_type, amount, biz_date)
        VALUES (nextval('ledger_seq'), 0, 'VATRPT', :h_dtlvat, :h_bizdate);
    if (sqlca.sqlcode < 0) { fprintf(stderr, "MARKER FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: base=%s dtl_vat=%ld inv_cnt=%ld supply=%ld inv_vat=%ld diff=%ld\n",
           ST_VATREPORT_TAG, bizdate, rec.dtl_vat, rec.inv_cnt, rec.inv_supply, rec.inv_vat,
           rec.inv_vat - rec.dtl_vat);

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