/*
 * rc_weekrate_batch.pgc - 주별 대사율 집계 배치 (커서 + XA): 최근 7영업일을 일자별로 순회하며 대사완료율을 rc_summary 에 upsert.
 * ATMI 클라이언트: tpinit/tpopen 으로 ECPG XA RM 를 열고 tpbegin 으로 ONE global tx
 * 를 시작, EXEC SQL 수행 후 tpcommit 이 XA 2PC 를 구동. 사용법: rc_weekrate_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_weekrate_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    long rows = 0;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_total, h_done, h_un;
    char h_day[16];
    EXEC SQL END DECLARE SECTION;

    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 DECLARE bcur CURSOR FOR
        SELECT to_char(d, 'YYYY-MM-DD'),
               (SELECT count(*) FROM purchase p WHERE p.biz_date = d),
               (SELECT count(*) FROM purchase p WHERE p.biz_date = d AND p.status IN ('M','S'))
        FROM generate_series(:h_bizdate::date - 6, :h_bizdate::date, interval '1 day') d
        ORDER BY d;
    EXEC SQL OPEN bcur;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH bcur INTO :h_day, :h_total, :h_done;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE bcur; tpabort(0); return 1; }
        h_un = h_total - h_done;
        EXEC SQL INSERT INTO rc_summary (biz_date, matched_cnt, unmatched_cnt, gross_amount, updated_at)
            VALUES (:h_day, :h_done, :h_un, 0, now())
            ON CONFLICT (biz_date) DO UPDATE SET matched_cnt = EXCLUDED.matched_cnt,
                unmatched_cnt = EXCLUDED.unmatched_cnt, updated_at = now();
        if (sqlca.sqlcode < 0) { fprintf(stderr, "UPS FAIL [%d]\n", sqlca.sqlcode); EXEC SQL CLOSE bcur; tpabort(0); return 1; }
        rows++;
    }
    EXEC SQL CLOSE bcur;

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> rc_weekrate_batch COMMIT: asof=%s days=%ld\n", bizdate, rows);

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