/*
 * lg_feerecog_batch.pgc - lg 수수료 수익 인식 배치 (커서 + XA).
 *
 * 당일 정산완료(S) 매입 수수료를 가맹점별로 묶어 가맹점당 한 장의
 * D:RECV / C:FEE_INC 균형 전표(FEE)로 전기한다. 가맹점 단위 전기이므로
 * 원장 라인에 merchant_id 가 남아 가맹점 잔액 대사에 쓰인다.
 * 모두 ONE global XA transaction 에서 수행.
 * Usage: lg_feerecog_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "lg_dbio.h"
#include "lg_feerecog_batch.h"

int main(int argc, char **argv)
{
    lg_feerecog_rec_t rec;
    long vid;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_merch[64];
    long h_fee;
    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 fr_cur CURSOR FOR
        SELECT merchant_id, coalesce(sum(fee), 0)
        FROM purchase WHERE biz_date = :h_bizdate AND status = 'S'
        GROUP BY merchant_id HAVING sum(fee) > 0
        ORDER BY merchant_id;
    EXEC SQL OPEN fr_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 fr_cur INTO :h_merch, :h_fee;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d]\n", sqlca.sqlcode); EXEC SQL CLOSE fr_cur; tpabort(0); return 1; }

        vid = lgdb_next_voucher_id();
        if (vid < 0) { EXEC SQL CLOSE fr_cur; tpabort(0); return 1; }
        if (lgdb_insert_voucher(vid, "FEE", 0, "P", rec.biz_date, "수수료 수익 인식 배치") < 0 ||
            lgdb_insert_line(vid, "RECV", "D", h_fee, h_merch, rec.biz_date, "posted") < 0 ||
            lgdb_insert_line(vid, "FEE_INC", "C", h_fee, h_merch, rec.biz_date, "posted") < 0 ||
            lgdb_upsert_merch_bal(h_merch, rec.biz_date) < 0)
            { EXEC SQL CLOSE fr_cur; tpabort(0); return 1; }
        rec.fee_total += h_fee;
        rec.merchants++;
        rec.vouchers++;
    }
    EXEC SQL CLOSE fr_cur;

    /* 인식 총액을 계정잔액에도 반영 (차=대 동액) */
    if (rec.fee_total > 0) {
        if (lgdb_upsert_acct_bal("RECV", rec.biz_date, rec.fee_total, 0) < 0 ||
            lgdb_upsert_acct_bal("FEE_INC", rec.biz_date, 0, rec.fee_total) < 0)
            { tpabort(0); return 1; }
    }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> lg_feerecog_batch COMMIT: %s 가맹점 %ld곳 %ld전표 수수료 %ld 인식\n",
           rec.biz_date, rec.merchants, rec.vouchers, rec.fee_total);

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