/*
 * lg_reverse_batch.pgc - lg 조정(ADJ) 전표 역분개 배치 (커서 + insert..select) (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_reverse_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];
    long h_src, h_new;
    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 rows = 0;
    EXEC SQL DECLARE lvb CURSOR FOR
        SELECT voucher_id FROM lg_voucher
        WHERE biz_date = :h_bizdate AND voucher_type = 'ADJ' AND status = 'P'
        ORDER BY voucher_id;
    EXEC SQL OPEN lvb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH lvb INTO :h_src;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE lvb; tpabort(0); return 1; }
        h_new = lgdb_next_voucher_id();
        if (h_new < 0) { EXEC SQL CLOSE lvb; tpabort(0); return 1; }
        if (lgdb_insert_voucher(h_new, "REVERSE", h_src, "P", bizdate, "조정역분개(배치)") < 0) { EXEC SQL CLOSE lvb; tpabort(0); return 1; }
        EXEC SQL INSERT INTO lg_ledger_line
            (line_id, voucher_id, acct, dc, amount, merchant_id, biz_date, status)
            SELECT nextval('lg_line_seq'), :h_new, acct,
                   CASE WHEN dc='D' THEN 'C' ELSE 'D' END, amount, merchant_id, :h_bizdate, 'posted'
            FROM lg_ledger_line WHERE voucher_id = :h_src;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE lvb; tpabort(0); return 1; }
        rows++;
    }
    EXEC SQL CLOSE lvb;
    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> lg_reverse_batch COMMIT: bizdate=%s 역분개=%ld전표\n", bizdate, rows);
    tpclose(); tpterm();
    return 0;
}
