/*
 * mm_partner_sync_batch.pgc - 제휴사 마스터-발급사 동기화 배치 (upsert 커서 + XA).
 *
 * 활성 발급사(mm_issuer)를 커서로 훑어 제휴사 코드(PARTNER 코드그룹)로 upsert 하고,
 * 발급사 마스터에서 사라졌거나 비활성인 제휴사 코드는 INACTIVE 로 내린다.
 * 전 구간 ONE global XA transaction.
 * host 변수는 전용 카피북 mm_partner_sync_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_partner_sync_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>

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

    EXEC SQL INCLUDE mm_partner_sync_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 psy CURSOR FOR
        SELECT issuer_cd, issuer_name FROM mm_issuer
        WHERE status = 'ACTIVE' ORDER BY issuer_cd;
    EXEC SQL OPEN psy;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH psy INTO :b_cd, :b_nm;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE psy; tpabort(0); return 1; }
        EXEC SQL INSERT INTO mm_code (code_group, code, code_name, status)
            VALUES ('PARTNER', :b_cd, :b_nm, 'ACTIVE')
            ON CONFLICT (code_group, code)
            DO UPDATE SET code_name = EXCLUDED.code_name, status = 'ACTIVE';
        if (sqlca.sqlcode < 0) { fprintf(stderr, "UPSERT FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE psy; tpabort(0); return 1; }
        synced++;
    }
    EXEC SQL CLOSE psy;

    /* 발급사 마스터에 없는(또는 비활성) 제휴사 코드는 은퇴 처리 */
    EXEC SQL UPDATE mm_code SET status = 'INACTIVE'
        WHERE code_group = 'PARTNER' AND status = 'ACTIVE'
          AND NOT EXISTS (SELECT 1 FROM mm_issuer i
                          WHERE i.issuer_cd = mm_code.code AND i.status = 'ACTIVE');
    if (sqlca.sqlcode < 0) { fprintf(stderr, "RETIRE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    retired = sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_partner_sync_batch COMMIT: 동기화=%ld건 은퇴=%ld건\n", synced, retired);

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