/*
 * lg_payrecon_batch.pgc - lg 원장-지급 대사 배치 (커서 + XA).
 *
 * 당일 가맹점 잔액 테이블(lg_merch_bal)의 순액(대변-차변 기준으로 재구성한
 * credit_total - debit_total)과 정산 지급액을 가맹점별로 비교, 최악 갭
 * 가맹점을 추적해 리포트한다. 모두 ONE global XA transaction 에서 수행.
 * Usage: lg_payrecon_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "lg_dbio.h"
#include "lg_payrecon_batch.h"

int main(int argc, char **argv)
{
    lg_payrecon_rec_t rec;
    long gap, absgap, worstabs = -1;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_merch[64];
    long h_cr, h_dr, h_paid;
    EXEC SQL END DECLARE SECTION;

    memset(&rec, 0, sizeof(rec));
    strncpy(rec.biz_date, (argc > 1) ? argv[1] : "2026-07-19", sizeof(rec.biz_date)-1);
    strncpy(h_bizdate, rec.biz_date, 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 pr_cur CURSOR FOR
        SELECT b.merchant_id, b.credit_total, b.debit_total,
               coalesce((SELECT sum(s.net) FROM settlement s
                         WHERE s.merchant_id = b.merchant_id
                           AND s.biz_date = b.biz_date), 0)
        FROM lg_merch_bal b WHERE b.biz_date = :h_bizdate
        ORDER BY b.merchant_id;
    EXEC SQL OPEN pr_cur;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH pr_cur INTO :h_merch, :h_cr, :h_dr, :h_paid;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d]\n", sqlca.sqlcode); EXEC SQL CLOSE pr_cur; tpabort(0); return 1; }
        gap = (h_cr - h_dr) - h_paid;
        rec.checked++;
        if (gap != 0) {
            rec.bad++;
            absgap = (gap > 0) ? gap : -gap;
            if (absgap > worstabs) {
                worstabs = absgap;
                rec.worst_gap = gap;
                strncpy(rec.worst_merch, h_merch, sizeof(rec.worst_merch)-1);
                rec.worst_merch[sizeof(rec.worst_merch)-1] = 0;
            }
        }
    }
    EXEC SQL CLOSE pr_cur;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> lg_payrecon_batch COMMIT: %s 점검 %ld곳 불일치 %ld곳 최악 %s(%ld)\n",
           rec.biz_date, rec.checked, rec.bad, rec.bad ? rec.worst_merch : "-", rec.worst_gap);

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