/*
 * au_merch_rank_batch.pgc - au 가맹점 승인 순위 배치 (window rank 커서 TOP-N, XA).
 *
 * 영업일의 가맹점별 유효 승인금액을 rank() 윈도우로 서열화한 서브쿼리를
 * 커서로 열어 상위 5곳만 페치, 1위 대비 점유율(%)과 함께 순위표를 찍는다.
 * Usage: au_merch_rank_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_merch_rank_batch.h"

long aub_rank_share_pct(long gross, long top_gross)
{
    return (top_gross > 0) ? (gross * 100L) / top_gross : 0;
}

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_merch[64];
    long h_rnk, h_gross, h_top;
    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;
    h_top = AU_MERCH_RANK_TOP;

    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 cmrb CURSOR FOR
        SELECT r.rnk, r.merchant_id, r.gross FROM (
            SELECT merchant_id, sum(amount) AS gross,
                   rank() OVER (ORDER BY sum(amount) DESC) AS rnk
            FROM au_authorization
            WHERE biz_date = :h_bizdate AND status IN ('A','M','S')
            GROUP BY merchant_id) r
        WHERE r.rnk <= :h_top
        ORDER BY r.rnk;
    EXEC SQL OPEN cmrb;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH cmrb INTO :h_rnk, :h_merch, :h_gross;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cmrb; tpabort(0); return 1; }
        if (ctx.listed == 0) {
            ctx.top_gross = h_gross;
            strncpy(ctx.top_merchant, h_merch, sizeof(ctx.top_merchant)-1);
        }
        ctx.listed++;
        ctx.grand_gross += h_gross;
        printf("    %ld위 %-10s %12ld원 (1위대비 %ld%%)\n",
               h_rnk, h_merch, h_gross, aub_rank_share_pct(h_gross, ctx.top_gross));
    }
    EXEC SQL CLOSE cmrb;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> au_merch_rank_batch COMMIT: bizdate=%s TOP%d=%ld곳 1위=%s(%ld원) 합계=%ld원\n",
           ctx.biz_date, AU_MERCH_RANK_TOP, ctx.listed, ctx.top_merchant, ctx.top_gross, ctx.grand_gross);

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