/*
 * mm_contract_renew_batch.pgc - 만기 도래 가맹 계약 자동갱신 배치 (GROUP BY 커서 + XA).
 *
 * 가맹점별 최종 계약 만기(after_val 최대값)가 오늘 이하인 건을 커서로 훑어
 * 만기일 기준 개월수 연장한 새 CONTRACT 이력을 적재한다 (해지 이력이 뒤따르는
 * 가맹점은 갱신 대상에서 제외). 전 구간 ONE global XA transaction.
 * host 변수는 전용 카피북 mm_contract_renew_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_contract_renew_batch [MONTHS=12]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mm_dbio.h"

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

    EXEC SQL INCLUDE mm_contract_renew_cpy;

    b_mon = (argc > 1) ? atol(argv[1]) : 12;
    if (b_mon < 1 || b_mon > 120) b_mon = 12;

    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 crn CURSOR FOR
        SELECT h.merchant_id, max(h.after_val)
        FROM mm_merch_hist h
        JOIN mm_merchant_ext m ON m.merchant_id = h.merchant_id AND m.status = 'ACTIVE'
        WHERE h.action = 'CONTRACT'
          AND NOT EXISTS (SELECT 1 FROM mm_merch_hist e
                          WHERE e.merchant_id = h.merchant_id AND e.action = 'CONT_END'
                            AND e.hist_id > h.hist_id)
        GROUP BY h.merchant_id
        HAVING max(h.after_val) <= to_char(current_date, 'YYYYMMDD')
        ORDER BY h.merchant_id;
    EXEC SQL OPEN crn;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH crn INTO :b_merch, :b_old;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE crn; tpabort(0); return 1; }
        EXEC SQL SELECT to_char(to_date(:b_old, 'YYYYMMDD') + :b_mon * interval '1 month', 'YYYYMMDD')
            INTO :b_new;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "CALC FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE crn; tpabort(0); return 1; }
        if (mmdb_insert_merch_hist(b_merch, "CONTRACT", b_old, b_new, "만기 도래 배치 자동갱신") < 0) {
            EXEC SQL CLOSE crn; tpabort(0); return 1;
        }
        renewed++;
    }
    EXEC SQL CLOSE crn;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_contract_renew_batch COMMIT: 연장=%ld개월 갱신=%ld건\n", b_mon, renewed);

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