/*
 * lg_journal_batch.pgc - lg 전표유형별 분개 통계 배치 (커서 GROUP BY) (XA 배치).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction; EXEC SQL work runs on that branch, then tpcommit drives XA 2PC.
 * Usage: lg_journal_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "lg_dbio.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    char h_type[16];
    long h_vc, h_lc;
    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; }

    long types = 0;
    EXEC SQL DECLARE ljb CURSOR FOR
        SELECT v.voucher_type, count(DISTINCT v.voucher_id), count(l.line_id)
        FROM lg_voucher v LEFT JOIN lg_ledger_line l ON l.voucher_id = v.voucher_id
        WHERE v.biz_date = :h_bizdate GROUP BY v.voucher_type ORDER BY v.voucher_type;
    EXEC SQL OPEN ljb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH ljb INTO :h_type, :h_vc, :h_lc;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE ljb; tpabort(0); return 1; }
        printf("    %-10s 전표=%ld 분개=%ld\n", h_type, h_vc, h_lc);
        types++;
    }
    EXEC SQL CLOSE ljb;
    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> lg_journal_batch COMMIT: bizdate=%s 유형=%ld종\n", bizdate, types);
    tpclose(); tpterm();
    return 0;
}
