/*
 * ac_apprgap_batch.pgc - ac 승인-매입 갭 양방향 대사 배치 (2단 점검, XA).
 *
 * ATMI client: 승인 없는 매입 금액과 매입 없는 고아 승인 건수를 양방향으로
 * 재고, 거절(approved=false) 승인이 달린 매입 수까지 3개 지표를 산출한다.
 * 갭이 있으면 종료코드 2.
 * Usage: ac_apprgap_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "ac_apprgap_batch.h"

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

    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_noap = 0, h_noamt = 0, h_orphan = 0, h_denied = 0;
    EXEC SQL END DECLARE SECTION;

    memset(&cx, 0, sizeof(cx));
    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(90, 0) < 0) { fprintf(stderr, "tpbegin FAIL: %s\n", tpstrerror(tperrno)); return 1; }

    /* (1) 승인 없는 매입: 건수 + 금액 */
    EXEC SQL SELECT count(*), coalesce(sum(u.amount), 0)
        INTO :h_noap, :h_noamt
        FROM purchase u
        WHERE u.biz_date = :h_bizdate AND u.status NOT IN ('C', 'V', 'P')
          AND NOT EXISTS (SELECT 1 FROM approval a
                          WHERE a.purchase_id = u.purchase_id AND a.approved = true);
    if (sqlca.sqlcode < 0) { fprintf(stderr, "noappr FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }

    /* (2) 매입 없는 고아 승인 */
    EXEC SQL SELECT count(*) INTO :h_orphan
        FROM approval a LEFT JOIN purchase u ON u.purchase_id = a.purchase_id
        WHERE u.purchase_id IS NULL;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "orphan FAIL [%d]\n", sqlca.sqlcode); tpabort(0); return 1; }

    /* (3) 거절 승인이 달린 영업일 매입 */
    EXEC SQL SELECT count(DISTINCT u.purchase_id) INTO :h_denied
        FROM purchase u JOIN approval a ON a.purchase_id = u.purchase_id
        WHERE u.biz_date = :h_bizdate AND a.approved = false;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "ac_apprgap_batch FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    cx.no_approval = h_noap; cx.no_appr_amt = h_noamt;
    cx.orphan_appr = h_orphan; cx.denied = h_denied;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> ac_apprgap_batch COMMIT: bizdate=%s no_appr=%ld(%ld) orphan=%ld denied=%ld\n",
           bizdate, cx.no_approval, cx.no_appr_amt, cx.orphan_appr, cx.denied);

    tpclose(); tpterm();
    return (cx.no_approval + cx.orphan_appr) > 0 ? 2 : 0;
}
