/*
 * mm_biz_hibernate_batch.pgc - 무거래 가맹점 휴면 전환 배치 (LEFT JOIN 커서 + XA).
 *
 * 최근 N일간 집계 매출이 전혀 없는 활성 가맹점을 DORMANT로 전환하고 DORMANT 이력을
 * 남긴다(자동 휴면). ONE global XA transaction.
 * host 변수는 mm_biz_hibernate_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_biz_hibernate_batch [DAYS=180]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mm_dbio.h"

int main(int argc, char **argv)
{
    EXEC SQL INCLUDE mm_biz_hibernate_cpy;
    b_hibernated = 0;
    b_days = (argc > 1) ? atol(argv[1]) : 180;
    if (b_days < 1) b_days = 180;

    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 hib CURSOR FOR
        SELECT me.merchant_id
        FROM mm_merchant_ext me
        LEFT JOIN merchant_summary ms
               ON ms.merchant_id = me.merchant_id AND ms.biz_date >= current_date - :b_days
        WHERE me.status = 'ACTIVE'
        GROUP BY me.merchant_id
        HAVING coalesce(sum(ms.gross_amount), 0) = 0
        ORDER BY me.merchant_id;
    EXEC SQL OPEN hib;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH hib INTO :b_merch;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE hib; tpabort(0); return 1; }
        EXEC SQL UPDATE mm_merchant_ext SET status = 'DORMANT', updated_at = now()
            WHERE merchant_id = :b_merch;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE hib; tpabort(0); return 1; }
        if (mmdb_insert_merch_hist(b_merch, "DORMANT", "ACTIVE", "DORMANT", "무거래 자동 휴면") < 0) {
            EXEC SQL CLOSE hib; tpabort(0); return 1;
        }
        b_hibernated++;
    }
    EXEC SQL CLOSE hib;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_biz_hibernate_batch COMMIT: 기간=%ld일 휴면=%ld건\n", b_days, b_hibernated);

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