/*
 * cm_purge_batch.pgc - cm 공통로그 보존기간 경과분 삭제 배치 (XA).
 *
 * ATMI client: opens the ECPG XA RM, begins ONE global transaction, deletes
 * cm_log rows older than cm_param LOG_KEEP_DAYS (기본 90일) from a cutoff biz_date,
 * then tpcommit drives XA 2PC. Usage: cm_purge_batch [YYYY-MM-DD(기준일)]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "cm_dbio.h"

int main(int argc, char **argv)
{
    char keep_s[128];
    long keep_days = 90;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_asof[16];
    long h_keep, h_deleted;
    EXEC SQL END DECLARE SECTION;

    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; }

    /* 보존일수는 파라미터에서 (없으면 90일 기본) */
    if (cmdb_get_param("LOG_KEEP_DAYS", keep_s) == 0) {
        long v = atol(keep_s);
        if (v > 0) keep_days = v;
    }
    h_keep = keep_days;

    /* 기준일: 인자 우선, 없으면 cm_param BIZ_DATE */
    if (argc > 1) {
        strncpy(h_asof, argv[1], sizeof(h_asof)-1); h_asof[sizeof(h_asof)-1] = 0;
    } else if (cmdb_get_param("BIZ_DATE", keep_s) == 0) {
        strncpy(h_asof, keep_s, sizeof(h_asof)-1); h_asof[sizeof(h_asof)-1] = 0;
    } else {
        strcpy(h_asof, "2026-07-19");
    }

    EXEC SQL DELETE FROM cm_log
        WHERE biz_date < (CAST(:h_asof AS date) - (:h_keep || ' days')::interval);
    if (sqlca.sqlcode < 0) {
        fprintf(stderr, "DELETE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        tpabort(0); return 1;
    }
    h_deleted = sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> cm_purge_batch COMMIT: asof=%s keep_days=%ld deleted=%ld\n",
           h_asof, keep_days, h_deleted);

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