/*
 * lg_deptpl_batch.pgc - lg 부문별 손익 집계 배치 (커서 + XA).
 *
 * 당일 매입을 업종/부문(category)별로 GROUP BY 하여 건수/매출/수수료 손익을
 * 산출하고 부문별 수수료 점유율(bps)을 계산해 리포트로 출력한다. 취소(C)
 * 매입은 제외. 조회 전용이지만 ONE XA transaction 규율은 동일하게 지킨다.
 * Usage: lg_deptpl_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "lg_dbio.h"
#include "lg_deptpl_batch.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_cat[32];
    long h_cnt, h_gross, h_fee, h_totfee;
    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 SELECT coalesce(sum(fee), 0) INTO :h_totfee
        FROM purchase WHERE biz_date = :h_bizdate AND status <> 'C';
    if (sqlca.sqlcode < 0) { fprintf(stderr, "SUM FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }

    EXEC SQL DECLARE dpb_cur CURSOR FOR
        SELECT category, count(*), coalesce(sum(amount), 0), coalesce(sum(fee), 0)
        FROM purchase WHERE biz_date = :h_bizdate AND status <> 'C'
        GROUP BY category ORDER BY 4 DESC;
    EXEC SQL OPEN dpb_cur;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    printf("--- 부문별 손익 (%s) ---\n", bizdate);
    for (;;) {
        EXEC SQL FETCH dpb_cur INTO :h_cat, :h_cnt, :h_gross, :h_fee;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d]\n", sqlca.sqlcode); EXEC SQL CLOSE dpb_cur; tpabort(0); return 1; }
        memset(&rec, 0, sizeof(rec));
        strncpy(rec.category, h_cat, sizeof(rec.category)-1);
        rec.txns = h_cnt; rec.gross = h_gross; rec.fee = h_fee;
        rec.share_bps = (h_totfee > 0) ? h_fee * 10000 / h_totfee : 0;
        printf("    %-12s %6ld건 매출 %12ld 수수료 %10ld (%ldbps)\n",
               rec.category, rec.txns, rec.gross, rec.fee, rec.share_bps);
        totfee += rec.fee;
        depts++;
    }
    EXEC SQL CLOSE dpb_cur;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> lg_deptpl_batch COMMIT: 부문 %ld개 총수수료손익 %ld\n", depts, totfee);

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