/*
 * cm_seqgc_batch.pgc - cm 일자별 채번 카운터 정리(GC) 배치 (XA).
 *
 * CM_SEQ_DAILY 가 만드는 일자별 카운터(seq_name = "<이름>:<YYYY-MM-DD>")
 * 중 보존일수(30일)가 지난 것을 골라 삭제한다. 키의 날짜부는
 * split_part 로 떼어 컷오프와 문자열 비교한다. 삭제 결과는 cm_log
 * (svc=SEQGC) 로 남긴다. Usage: cm_seqgc_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "cm_seqgc_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    cm_seqgc_rec_t rec = { 0, 0 };
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_cutoff[16], h_msg[96];
    long h_scan = 0, h_keep;
    EXEC SQL END DECLARE SECTION;

    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    h_keep = CM_SEQGC_KEEP_DAYS;

    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 SELECT (:h_bizdate::date - :h_keep::int)::text INTO :h_cutoff;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }

    EXEC SQL SELECT count(*) INTO :h_scan FROM cm_seq WHERE seq_name LIKE '%:%';
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    rec.scanned = h_scan;

    EXEC SQL DELETE FROM cm_seq
        WHERE seq_name LIKE '%:%'
          AND split_part(seq_name, ':', 2) < :h_cutoff;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "cm_seqgc_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.deleted = (long)sqlca.sqlerrd[2];

    snprintf(h_msg, sizeof(h_msg), "SEQGC cutoff=%s scanned=%ld deleted=%ld",
             h_cutoff, rec.scanned, rec.deleted);
    EXEC SQL INSERT INTO cm_log (log_id, svc_name, log_level, msg, biz_date)
        VALUES (nextval('cm_log_seq'), 'SEQGC', 'I', :h_msg, :h_bizdate);
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> cm_seqgc_batch COMMIT: 컷오프=%s 대상=%ld 삭제=%ld\n",
           h_cutoff, rec.scanned, rec.deleted);

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