/*
 * mm_contract_expire_batch.pgc - 만기 경과 계약 만료 처리 배치 (커서 + XA).
 *
 * 각 가맹점의 최신 CONTRACT 이력 만기일이 오늘 이전이고 아직 CONTRACT_EXP가
 * 기록되지 않은 건에 대해 CONTRACT_EXP 이력을 적재한다(만료 확정). ONE XA txn.
 * host 변수는 mm_contract_expire_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_contract_expire_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mm_dbio.h"

int main(int argc, char **argv)
{
    (void)argc; (void)argv;
    EXEC SQL INCLUDE mm_contract_expire_cpy;
    b_expired = 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 DECLARE cex CURSOR FOR
        SELECT h.merchant_id, h.after_val
        FROM mm_merch_hist h
        WHERE h.action = 'CONTRACT'
          AND h.hist_id = (SELECT max(h2.hist_id) FROM mm_merch_hist h2
                           WHERE h2.merchant_id = h.merchant_id AND h2.action = 'CONTRACT')
          AND h.after_val < to_char(current_date, 'YYYYMMDD')
          AND NOT EXISTS (SELECT 1 FROM mm_merch_hist e
                          WHERE e.merchant_id = h.merchant_id AND e.action = 'CONTRACT_EXP'
                            AND e.hist_id > h.hist_id)
        ORDER BY h.merchant_id;
    EXEC SQL OPEN cex;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH cex INTO :b_merch, :b_end;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cex; tpabort(0); return 1; }
        if (mmdb_insert_merch_hist(b_merch, "CONTRACT_EXP", b_end, "EXPIRED", "만기 경과 자동 만료") < 0) {
            EXEC SQL CLOSE cex; tpabort(0); return 1;
        }
        b_expired++;
    }
    EXEC SQL CLOSE cex;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_contract_expire_batch COMMIT: 만료=%ld건\n", b_expired);

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