/*
 * mm_audit_compact_batch.pgc - 감사 이력 압축 배치 (요약행 생성 후 원본 삭제 + XA).
 *
 * 보존일수를 넘긴 가맹점별 이력이 임계 건수를 초과하면 건수를 담은 AUDIT_SUM
 * 요약행 1건을 남기고 해당 구간의 원본 이력을 삭제해 mm_merch_hist 를 압축한다.
 * (AUDIT_SUM 자신은 삭제 대상에서 제외.) 전 구간 ONE global XA transaction.
 * host 변수는 전용 카피북 mm_audit_compact_cpy.h 를 EXEC SQL INCLUDE.
 * Usage: mm_audit_compact_batch [DAYS=365] [KEEP_THRESHOLD=10]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mm_dbio.h"

int main(int argc, char **argv)
{
    long merchants = 0, removed = 0;
    char summary[96];

    EXEC SQL INCLUDE mm_audit_compact_cpy;

    b_days = (argc > 1) ? atol(argv[1]) : 365;
    b_keep = (argc > 2) ? atol(argv[2]) : 10;
    if (b_days < 30) b_days = 365;
    if (b_keep < 1) b_keep = 10;

    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(120, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    EXEC SQL DECLARE acp CURSOR FOR
        SELECT merchant_id, count(*) FROM mm_merch_hist
        WHERE created_at < now() - :b_days * interval '1 day'
          AND action <> 'AUDIT_SUM'
        GROUP BY merchant_id
        HAVING count(*) > :b_keep
        ORDER BY merchant_id;
    EXEC SQL OPEN acp;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH acp INTO :b_merch, :b_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE acp; tpabort(0); return 1; }
        snprintf(summary, sizeof(summary), "보존기한 경과 이력 %ld건 압축 요약", b_cnt);
        if (mmdb_insert_merch_hist(b_merch, "AUDIT_SUM", "", "", summary) < 0) {
            EXEC SQL CLOSE acp; tpabort(0); return 1;
        }
        EXEC SQL DELETE FROM mm_merch_hist
            WHERE merchant_id = :b_merch
              AND created_at < now() - :b_days * interval '1 day'
              AND action <> 'AUDIT_SUM';
        if (sqlca.sqlcode < 0) { fprintf(stderr, "DELETE FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE acp; tpabort(0); return 1; }
        removed += sqlca.sqlerrd[2];
        merchants++;
    }
    EXEC SQL CLOSE acp;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mm_audit_compact_batch COMMIT: 압축 가맹점=%ld 삭제 이력=%ld건\n", merchants, removed);

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