/*
 * rc_dupchk_batch.pgc - 중복 대사 정리 배치 (커서 + XA).
 * 당일 두 번 이상 대사된 매입을 GROUP BY/HAVING 커서로 찾아, 매입마다 최초
 * (min match_id) 대사만 남기고 나머지 중복 행을 ROLLBACK 상태로 정리한다.
 * 사용법: rc_dupchk_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"
#include "rc_dupchk_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    rc_dupchk_rec_t rec;
    long pids = 0, cleaned = 0;

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_pid;
    EXEC SQL END DECLARE SECTION;
    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 cdb CURSOR FOR
        SELECT purchase_id FROM rc_match_log
        WHERE biz_date = :h_bizdate
        GROUP BY purchase_id HAVING count(*) > 1
        ORDER BY purchase_id;
    EXEC SQL OPEN cdb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH cdb INTO :h_pid;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE cdb; tpabort(0); return 1; }
        rec.pid = h_pid;
        EXEC SQL UPDATE rc_match_log SET status = 'ROLLBACK', updated_at = now()
            WHERE biz_date = :h_bizdate AND purchase_id = :h_pid
              AND match_id <> (SELECT min(match_id) FROM rc_match_log
                               WHERE biz_date = :h_bizdate AND purchase_id = :h_pid);
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cdb; tpabort(0); return 1; }
        rec.dup_rows = sqlca.sqlerrd[2];
        cleaned += rec.dup_rows;
        pids++;
    }
    EXEC SQL CLOSE cdb;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: bizdate=%s dup_purchases=%ld cleaned_rows=%ld\n",
           RC_DUPCHK_TAG, bizdate, pids, cleaned);

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