/*
 * rc_diff_batch.pgc - rc 금액 차이 배치 (커서 + XA).
 *
 * 당일 매입 중 정산 원장(SETTLE) 합계가 net 과 다른 건을 커서로 순회하며 rc_diff
 * 에 AMT 차이 라인을 기록한다 (ONE global XA tx). 사용법: rc_diff_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_id, h_pid, h_exp, h_act, h_diff;
    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 rdc CURSOR FOR
        SELECT p.purchase_id, p.net,
               coalesce((SELECT sum(l.amount) FROM ledger l
                         WHERE l.purchase_id = p.purchase_id AND l.entry_type = 'SETTLE'), 0)
        FROM purchase p
        WHERE p.biz_date = :h_bizdate
        ORDER BY p.purchase_id;
    EXEC SQL OPEN rdc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH rdc INTO :h_pid, :h_exp, :h_act;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE rdc; tpabort(0); return 1; }
        if (h_exp == h_act) continue;              /* 일치 건은 건너뜀 */
        h_diff = h_exp - h_act;
        EXEC SQL SELECT nextval('rc_diff_seq') INTO :h_id;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE rdc; tpabort(0); return 1; }
        EXEC SQL INSERT INTO rc_diff (diff_id, purchase_id, expected_amt, actual_amt, diff_amt, diff_kind, biz_date)
            VALUES (:h_id, :h_pid, :h_exp, :h_act, :h_diff, 'AMT', :h_bizdate);
        if (sqlca.sqlcode < 0) { fprintf(stderr, "INSERT FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE rdc; tpabort(0); return 1; }
        rows++;
    }
    EXEC SQL CLOSE rdc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> rc_diff_batch COMMIT: bizdate=%s diff_rows=%ld\n", bizdate, rows);

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