/*
 * lg_trialload_batch.pgc - lg 시산표 집계 적재 (INSERT..SELECT 배치, XA).
 *
 * Aggregates ledger lines into per-account debit/credit/diff and upserts the
 * trial balance with a single INSERT..SELECT, inside ONE XA transaction.
 * Usage: lg_trialload_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "lg_trialload_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    lg_trialload_rec_t rec;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_accts;
    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 INSERT INTO lg_trial_bal (acct, biz_date, debit_total, credit_total, diff)
        SELECT acct, :h_bizdate,
               coalesce(sum(amount) FILTER (WHERE dc = 'D'),0),
               coalesce(sum(amount) FILTER (WHERE dc = 'C'),0),
               coalesce(sum(amount) FILTER (WHERE dc = 'D'),0)
             - coalesce(sum(amount) FILTER (WHERE dc = 'C'),0)
        FROM lg_ledger_line WHERE biz_date = :h_bizdate GROUP BY acct
        ON CONFLICT (acct, biz_date) DO UPDATE
        SET debit_total = EXCLUDED.debit_total, credit_total = EXCLUDED.credit_total,
            diff = EXCLUDED.diff, updated_at = now();
    if (sqlca.sqlcode < 0) { fprintf(stderr, "lg_trialload_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    h_accts = sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }

    strncpy(rec.biz_date, bizdate, sizeof(rec.biz_date)-1); rec.biz_date[sizeof(rec.biz_date)-1] = 0;
    rec.accts_loaded = h_accts;
    printf(">>> lg_trialload_batch COMMIT: date=%s accts_loaded=%ld\n", rec.biz_date, rec.accts_loaded);

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