/*
 * au_auth_topcard_dbio.pgc - au 모듈 DB 접근 함수 세트 (au_auth_topcard_dbio), archived into libaudbio.a.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 * Shape: row_number() OVER (PARTITION BY card_no ORDER BY amount DESC) 커서 스캔.
 */
#include <string.h>
#include <userlog.h>
#include "au_auth_topcard_dbio.h"

/* 카드별 최고 승인행(rn=1)만 세어 서로 다른 카드 수를 반환하고 최고 금액은 peak_out. */
long audb_topcard_distinct(const char *bizdate, long *peak_out)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_card[24];
    long h_rn, h_amt, cards = 0, peak = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL DECLARE tcc CURSOR FOR
        SELECT row_number() OVER (PARTITION BY card_no ORDER BY amount DESC) AS rn, card_no, amount
        FROM au_authorization WHERE biz_date = :h_bizdate;
    EXEC SQL OPEN tcc;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH tcc INTO :h_rn, :h_card, :h_amt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE tcc; return -1; }
        if (h_rn == 1) {
            cards++;
            if (h_amt > peak) peak = h_amt;
        }
    }
    EXEC SQL CLOSE tcc;
    *peak_out = peak;
    return cards;
}
