/*
 * mm_rel_orphan_batch.pgc - 대표-하위 가맹점 관계 정합성 정리 배치 (NOT EXISTS 커서 + XA).
 *
 * 대표가맹점(code_name)이 더 이상 활성이 아닌 MERCH_REL 관계 행을 커서로 찾아
 * INACTIVE 로 내리고 하위가맹점 이력(REL_UNLINK)을 남긴다.
 * 전 구간 ONE global XA transaction.
 * host 변수는 전용 카피북 mm_rel_orphan_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_rel_orphan_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mm_dbio.h"

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

    EXEC SQL INCLUDE mm_rel_orphan_cpy;

    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 rox CURSOR FOR
        SELECT c.code, c.code_name FROM mm_code c
        WHERE c.code_group = 'MERCH_REL' AND c.status = 'ACTIVE'
          AND NOT EXISTS (SELECT 1 FROM mm_merchant_ext m
                          WHERE m.merchant_id = c.code_name AND m.status = 'ACTIVE')
        ORDER BY c.code;
    EXEC SQL OPEN rox;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH rox INTO :b_child, :b_parent;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE rox; tpabort(0); return 1; }
        EXEC SQL UPDATE mm_code SET status = 'INACTIVE'
            WHERE code_group = 'MERCH_REL' AND code = :b_child;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "UPDATE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE rox; tpabort(0); return 1; }
        if (mmdb_insert_merch_hist(b_child, "REL_UNLINK", b_parent, "", "대표가맹점 비활성 배치 해제") < 0) {
            EXEC SQL CLOSE rox; tpabort(0); return 1;
        }
        cleaned++;
    }
    EXEC SQL CLOSE rox;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_rel_orphan_batch COMMIT: 관계 해제=%ld건\n", cleaned);

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