/*
 * mg_dupmark_batch.pgc - mg 중복 STAN 전문 마킹 배치 (커서 + XA).
 *
 * 당일 STAN 별 건수를 group by 커서로 훑어 2건 이상인 STAN 마다, 최소 msg_id(원본)만
 * 남기고 나머지를 rc=94/status=X 로 폐기 마킹한다 (중복검출의 대량 마킹 일배치판).
 * Usage: mg_dupmark_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "mg_dupmark_batch.h"

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];
    long h_stan, h_cnt, h_keep;
    EXEC SQL END DECLARE SECTION;
    mg_dupmark_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 dmc CURSOR FOR
        SELECT stan, count(*) FROM mg_msg_log WHERE biz_date = :h_bizdate
        GROUP BY stan HAVING count(*) > 1 ORDER BY stan;
    EXEC SQL OPEN dmc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    for (;;) {
        EXEC SQL FETCH dmc INTO :h_stan, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE dmc; tpabort(0); return 1; }
        rec.dup_stans++;

        EXEC SQL SELECT min(msg_id) INTO :h_keep
            FROM mg_msg_log WHERE biz_date = :h_bizdate AND stan = :h_stan;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE dmc; tpabort(0); return 1; }

        EXEC SQL UPDATE mg_msg_log SET rc = '94', status = 'X'
            WHERE biz_date = :h_bizdate AND stan = :h_stan AND msg_id <> :h_keep;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE dmc; tpabort(0); return 1; }
        rec.marked += (long)sqlca.sqlerrd[2];
    }
    EXEC SQL CLOSE dmc;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> mg_dupmark_batch COMMIT: bizdate=%s 중복STAN=%ld 폐기마킹=%ld건\n",
           bizdate, rec.dup_stans, rec.marked);

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