/*
 * au_night_auth_batch.pgc - au 심야 승인 집계 배치 (시간대 조건 집계, XA).
 *
 * 영업일의 승인 접수를 심야(23시~06시)/주간으로 나눠 한 번의 조건부 FILTER
 * 집계로 건수·금액을 뽑고, 심야건수 비중(bps)을 계산해 등급을 판정한다.
 * ATMI client: ONE global transaction, tpcommit 이 XA 2PC 를 몬다.
 * Usage: au_night_auth_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_night_auth_batch.h"

const char *aub_night_grade(long bps)
{
    if (bps >= 4000) return "ALERT";        /* 심야비중 40% 이상 */
    if (bps >= 2000) return "ELEVATED";
    return "LOW";
}

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_ncnt = 0, h_namt = 0, h_dcnt = 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(*) FILTER (WHERE EXTRACT(HOUR FROM created_at) >= 23
                                OR EXTRACT(HOUR FROM created_at) < 6),
            coalesce(sum(amount) FILTER (WHERE EXTRACT(HOUR FROM created_at) >= 23
                                            OR EXTRACT(HOUR FROM created_at) < 6), 0),
            count(*) FILTER (WHERE EXTRACT(HOUR FROM created_at) >= 6
                               AND EXTRACT(HOUR FROM created_at) < 23)
        INTO :h_ncnt, :h_namt, :h_dcnt
        FROM au_authorization WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "au_night_auth_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    ctx.night_count = h_ncnt;
    ctx.night_gross = h_namt;
    ctx.day_count = h_dcnt;
    ctx.night_bps = (h_ncnt + h_dcnt > 0) ? (h_ncnt * 10000L) / (h_ncnt + h_dcnt) : 0;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> au_night_auth_batch COMMIT: bizdate=%s night=%ld(%ld원) day=%ld 심야비중=%ldbps grade=%s\n",
           ctx.biz_date, ctx.night_count, ctx.night_gross, ctx.day_count,
           ctx.night_bps, aub_night_grade(ctx.night_bps));

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