/*
 * mm_term_scrap_batch.pgc - 장기 정지 단말 일괄 폐기 배치 (커서 + UPDATE + 이력 + XA).
 *
 * SUSPENDED 상태로 보존일수 이상 경과한 단말을 커서로 훑어 SCRAPPED 로 전환하고,
 * 소속 가맹점 이력(TERM_SCRAP)을 남긴다. 전 구간 ONE global XA transaction.
 * host 변수는 전용 카피북 mm_term_scrap_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_term_scrap_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)
{
    long scrapped = 0;

    EXEC SQL INCLUDE mm_term_scrap_cpy;

    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 tsc CURSOR FOR
        SELECT terminal_id, merchant_id FROM mm_terminal
        WHERE status = 'SUSPENDED'
          AND created_at < now() - :b_days * interval '1 day'
        ORDER BY terminal_id;
    EXEC SQL OPEN tsc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH tsc INTO :b_term, :b_merch;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE tsc; tpabort(0); return 1; }
        EXEC SQL UPDATE mm_terminal SET status = 'SCRAPPED' WHERE terminal_id = :b_term;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "UPDATE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE tsc; tpabort(0); return 1; }
        if (mmdb_insert_merch_hist(b_merch, "TERM_SCRAP", "SUSPENDED", "SCRAPPED", "장기 정지 단말 배치 폐기") < 0) {
            EXEC SQL CLOSE tsc; tpabort(0); return 1;
        }
        scrapped++;
    }
    EXEC SQL CLOSE tsc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_term_scrap_batch COMMIT: 기준=%ld일 폐기=%ld대\n", b_days, scrapped);

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