/*
 * vl_sales_batch.pgc - 매입-정산 대사검증 배치 (커서 JOIN + XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction, an EXEC SQL cursor JOINs 정산완료(status='S') 매입 against its
 * settlement rows for a biz_date; any purchase whose settled net != sum of its
 * settlement net (or with no settlement) is written to vl_suspect (via the
 * linked dbio lib), then tpcommit drives XA 2PC.
 * Usage: vl_sales_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "vl_dbio.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_pid, h_pnet, h_snet;
    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; }

    /* 매입(정산완료) LEFT JOIN 정산합계 - 불일치/누락 추출 */
    EXEC SQL DECLARE vsc CURSOR FOR
        SELECT p.purchase_id, p.net, coalesce(s.snet, 0)
        FROM purchase p
        LEFT JOIN (SELECT purchase_id, sum(net) AS snet FROM settlement
                   GROUP BY purchase_id) s ON s.purchase_id = p.purchase_id
        WHERE p.biz_date = :h_bizdate AND p.status = 'S'
        ORDER BY p.purchase_id;
    EXEC SQL OPEN vsc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH vsc INTO :h_pid, :h_pnet, :h_snet;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE vsc; tpabort(0); return 1; }
        scanned++;
        if (h_snet != h_pnet) {
            if (vldb_insert_suspect(h_pid, "LEDGER_MIS", "CRIT",
                                    "매입-정산 대사 불일치", bizdate) < 0) {
                EXEC SQL CLOSE vsc; tpabort(0); return 1;
            }
            flagged++;
        }
    }
    EXEC SQL CLOSE vsc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> vl_sales_batch COMMIT: bizdate=%s 검사=%ld 적출=%ld\n", bizdate, scanned, flagged);

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