/*
 * mg_panaudit_batch.pgc - mg 비마스킹 PAN 적발/마스킹 배치 (행단위 커서 갱신 + XA).
 *
 * pan 에 '*' 가 전혀 없는(=평문 의심) 당일 전문을 커서로 적발해
 * BIN(앞6)/뒤4 보존 마스킹으로 행마다 덮어쓴다 (정보보호 일제 점검).
 * Usage: mg_panaudit_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mg_panaudit_batch.h"

/* 앞6/뒤4 보존, 나머지 '*' 치환 (12자리 미만은 전부 '*'). */
static void pan_conceal(const char *in, char *out)
{
    int i, n = (int)strlen(in);
    if (n > 19) n = 19;
    for (i = 0; i < n; i++)
        out[i] = (n >= 12 && (i < 6 || i >= n - 4)) ? in[i] : '*';
    out[n] = 0;
}

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_pan[24], h_masked[24];
    long h_id;
    EXEC SQL END DECLARE SECTION;
    mg_panaudit_rec_t rec;
    memset(&rec, 0, sizeof(rec));

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

    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 pab CURSOR FOR
        SELECT msg_id, pan FROM mg_msg_log
        WHERE biz_date = :h_bizdate AND pan <> '' AND position('*' in pan) = 0;
    EXEC SQL OPEN pab;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH pab INTO :h_id, :h_pan;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE pab; tpabort(0); return 1; }
        rec.inspected++;
        pan_conceal(h_pan, h_masked);
        EXEC SQL UPDATE mg_msg_log SET pan = :h_masked WHERE msg_id = :h_id;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "마스킹 FAIL msg_id=%ld [%d]\n", h_id, sqlca.sqlcode); EXEC SQL CLOSE pab; tpabort(0); return 1; }
        rec.masked++;
    }
    EXEC SQL CLOSE pab;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mg_panaudit_batch COMMIT: bizdate=%s 적발=%ld건 마스킹=%ld건\n",
           bizdate, rec.inspected, rec.masked);

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