/*
 * au_dup_auth_batch.pgc - au 중복승인 검출 배치 (다중키 GROUP 커서, XA).
 *
 * 영업일의 승인(A/M/S) 건을 카드+가맹점+금액 3중 키로 그룹핑해 2건 이상
 * 반복된 그룹을 커서로 뽑고, 그룹마다 원거래 1건을 제외한 잉여 승인건수와
 * 금액(중복 환불 예상액)을 적산해 보고한다.
 * Usage: au_dup_auth_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_dup_auth_batch.h"

long aub_dup_extra(long group_cnt)
{
    return (group_cnt > 1) ? group_cnt - 1 : 0;
}

int main(int argc, char **argv)
{
    au_dup_auth_ctx_t ctx;
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_card[24], h_merch[64];
    long h_amt, h_cnt;
    EXEC SQL END DECLARE SECTION;

    memset(&ctx, 0, sizeof(ctx));
    strncpy(ctx.biz_date, bizdate, sizeof(ctx.biz_date)-1);
    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 cdab CURSOR FOR
        SELECT card_no, merchant_id, amount, count(*)
        FROM au_authorization
        WHERE biz_date = :h_bizdate AND status IN ('A','M','S')
        GROUP BY card_no, merchant_id, amount
        HAVING count(*) >= 2
        ORDER BY count(*) DESC, card_no;
    EXEC SQL OPEN cdab;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH cdab INTO :h_card, :h_merch, :h_amt, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cdab; tpabort(0); return 1; }
        ctx.dup_groups++;
        ctx.extra_auths += aub_dup_extra(h_cnt);
        ctx.extra_gross += aub_dup_extra(h_cnt) * h_amt;
        printf("    중복그룹 card=%.6s** merch=%s amt=%ld x%ld\n", h_card, h_merch, h_amt, h_cnt);
    }
    EXEC SQL CLOSE cdab;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> au_dup_auth_batch COMMIT: bizdate=%s 중복그룹=%ld 잉여승인=%ld건 %ld원\n",
           ctx.biz_date, ctx.dup_groups, ctx.extra_auths, ctx.extra_gross);

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