/*
 * mm_grade_recalc_batch.pgc - 가맹점 등급 재산정 배치 (누적매출 커서 + XA).
 *
 * ATMI client: tpinit/tpopen open the ECPG XA RM, tpbegin starts ONE global
 * transaction, an EXEC SQL cursor sums each merchant's 누적 매출(gross) from
 * merchant_summary, derives a grade (S/A/B/C) and UPDATEs mm_merchant_ext (via
 * the linked dbio lib), then tpcommit drives XA 2PC.
 * Usage: mm_grade_recalc_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mm_dbio.h"

/* 누적매출 -> 등급 임계 (원): S>=10억, A>=3억, B>=5천만, 그 외 C */
static const char *grade_of(long gross)
{
    if (gross >= 1000000000L) return "S";
    if (gross >=  300000000L) return "A";
    if (gross >=   50000000L) return "B";
    return "C";
}

int main(int argc, char **argv)
{
    long rows = 0;
    (void)argc; (void)argv;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_merch[64];
    long h_gross;
    EXEC SQL END DECLARE SECTION;

    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; }

    /* 가맹점별 누적 매출 = merchant_summary.gross_amount 합계 */
    EXEC SQL DECLARE grc CURSOR FOR
        SELECT ms.merchant_id, coalesce(sum(ms.gross_amount),0)
        FROM merchant_summary ms
        JOIN mm_merchant_ext me ON me.merchant_id = ms.merchant_id
        WHERE me.status = 'ACTIVE'
        GROUP BY ms.merchant_id ORDER BY ms.merchant_id;
    EXEC SQL OPEN grc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH grc INTO :h_merch, :h_gross;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE grc; tpabort(0); return 1; }
        if (mmdb_update_merchant_grade(h_merch, grade_of(h_gross)) < 0) {
            EXEC SQL CLOSE grc; tpabort(0); return 1;
        }
        if (mmdb_insert_merch_hist(h_merch, "GRADE", "", grade_of(h_gross), "배치 재산정") < 0) {
            EXEC SQL CLOSE grc; tpabort(0); return 1;
        }
        rows++;
    }
    EXEC SQL CLOSE grc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_grade_recalc_batch COMMIT: 재산정 가맹점=%ld\n", rows);

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