/*
 * au_issuer_mix_batch.pgc - au 발급사망 구성비 배치 (GROUP BY 커서 + 백분율, XA).
 *
 * 영업일 승인 접수를 카드번호 선두 자리로 그룹핑한 커서를 순회하며
 * 카드망(AMEX/VISA/MC/LOCAL/ETC)별 건수와 구성비(%)를 출력하고
 * 최다 카드망을 찾아 보고한다.
 * Usage: au_issuer_mix_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_issuer_mix_batch.h"

const char *aub_issuer_network(char lead)
{
    switch (lead) {
    case '3': return "AMEX";
    case '4': return "VISA";
    case '5': return "MC";
    case '6': return "LOCAL";
    default:  return "ETC";
    }
}

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_lead[4];
    long h_cnt, h_total = 0;
    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 SELECT count(*) INTO :h_total FROM au_authorization WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "COUNT FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    ctx.total = h_total;

    EXEC SQL DECLARE cimb CURSOR FOR
        SELECT substr(card_no, 1, 1), count(*)
        FROM au_authorization WHERE biz_date = :h_bizdate
        GROUP BY substr(card_no, 1, 1)
        ORDER BY count(*) DESC;
    EXEC SQL OPEN cimb;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH cimb INTO :h_lead, :h_cnt;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE cimb; tpabort(0); return 1; }
        ctx.networks++;
        if (h_cnt > ctx.top_count) {
            ctx.top_count = h_cnt;
            strncpy(ctx.top_network, aub_issuer_network(h_lead[0]), sizeof(ctx.top_network)-1);
        }
        printf("    망 %-5s : %6ld건 (%3ld%%)\n", aub_issuer_network(h_lead[0]), h_cnt,
               (ctx.total > 0) ? (h_cnt * 100L) / ctx.total : 0);
    }
    EXEC SQL CLOSE cimb;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> au_issuer_mix_batch COMMIT: bizdate=%s 망수=%ld 총=%ld 최다=%s(%ld건)\n",
           ctx.biz_date, ctx.networks, ctx.total, ctx.top_network, ctx.top_count);

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