/*
 * au_delay_watch_batch.pgc - au 승인 체류시간 감시 배치 (EPOCH 다중구간 집계, XA).
 *
 * 미매입 승인(A) 전체의 체류시간을 EPOCH 초로 환산해 평균/최대와
 * 1시간·24시간 초과 구간별 건수를 한 번의 집계로 뽑아, 최악 체류 건의
 * 지연구간 라벨(FRESH/AGING/STALE/CRITICAL)을 판정한다.
 * Usage: au_delay_watch_batch
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "au_delay_watch_batch.h"

const char *aub_delay_bucket(long age_sec)
{
    if (age_sec >= 86400) return "CRITICAL";
    if (age_sec >= 3600)  return "STALE";
    if (age_sec >= 600)   return "AGING";
    return "FRESH";
}

int main(int argc, char **argv)
{
    au_delay_watch_ctx_t ctx;

    EXEC SQL BEGIN DECLARE SECTION;
    long h_cnt = 0, h_avg = 0, h_max = 0, h_o1h = 0, h_o1d = 0;
    EXEC SQL END DECLARE SECTION;

    memset(&ctx, 0, sizeof(ctx));

    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(*),
                    CAST(coalesce(avg(EXTRACT(EPOCH FROM now() - created_at)),0) AS bigint),
                    CAST(coalesce(max(EXTRACT(EPOCH FROM now() - created_at)),0) AS bigint),
                    count(*) FILTER (WHERE created_at < now() - interval '1 hour'),
                    count(*) FILTER (WHERE created_at < now() - interval '24 hours')
        INTO :h_cnt, :h_avg, :h_max, :h_o1h, :h_o1d
        FROM au_authorization
        WHERE status = 'A' AND captured_at IS NULL;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "au_delay_watch_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    ctx.pending = h_cnt;
    ctx.avg_age_sec = h_avg;
    ctx.max_age_sec = h_max;
    ctx.over_1h = h_o1h;
    ctx.over_1d = h_o1d;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> au_delay_watch_batch COMMIT: 미매입=%ld 평균=%lds 최대=%lds(%s) 1h초과=%ld 24h초과=%ld\n",
           ctx.pending, ctx.avg_age_sec, ctx.max_age_sec,
           aub_delay_bucket(ctx.max_age_sec), ctx.over_1h, ctx.over_1d);

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