/*
 * rc_closeday_batch.pgc - 일마감 대사 확정 배치 (XA).
 * 미해결 예외/보류 잔량이 있으면 마감을 거부(exit 2)하고, 없으면 요약을
 * ON CONFLICT upsert 로 확정한 뒤 당일 MATCHED 를 CONFIRMED 로 전환한다.
 * 사용법: rc_closeday_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "rc_dbio.h"
#include "rc_closeday_batch.h"

int main(int argc, char **argv)
{
    rc_closeday_rec_t rec;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16];
    long h_open, h_hold, h_mat, h_unm, h_gross, h_conf;
    EXEC SQL END DECLARE SECTION;

    strncpy(rec.day, (argc > 1) ? argv[1] : "2026-07-19", sizeof(rec.day)-1);
    rec.day[sizeof(rec.day)-1] = 0;
    strcpy(h_bizdate, rec.day);

    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_open FROM rc_exception
        WHERE biz_date = :h_bizdate AND resolved = false;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    EXEC SQL SELECT count(*) INTO :h_hold FROM rc_match_log
        WHERE biz_date = :h_bizdate AND status = 'HOLD';
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    if (h_open > 0 || h_hold > 0) {
        fprintf(stderr, "%s REFUSED: open_exceptions=%ld holds=%ld\n",
                RC_CLOSEDAY_TAG, h_open, h_hold);
        tpabort(0); tpclose(); tpterm();
        return 2;
    }

    EXEC SQL SELECT coalesce(sum(CASE WHEN status = 'MATCHED' THEN 1 ELSE 0 END),0),
               coalesce(sum(CASE WHEN status = 'EXCEPTION' THEN 1 ELSE 0 END),0),
               coalesce(sum(CASE WHEN status = 'MATCHED' THEN amount ELSE 0 END),0)
        INTO :h_mat, :h_unm, :h_gross
        FROM rc_match_log WHERE biz_date = :h_bizdate;
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    rec.matched = h_mat; rec.unmatched = h_unm; rec.gross = h_gross;

    EXEC SQL INSERT INTO rc_summary (biz_date, matched_cnt, unmatched_cnt, gross_amount, updated_at)
        VALUES (:h_bizdate, :h_mat, :h_unm, :h_gross, now())
        ON CONFLICT (biz_date) DO UPDATE
        SET matched_cnt = EXCLUDED.matched_cnt,
            unmatched_cnt = EXCLUDED.unmatched_cnt,
            gross_amount = EXCLUDED.gross_amount,
            updated_at = now();
    if (sqlca.sqlcode < 0) { fprintf(stderr, "%s UPSERT FAIL [%d] %s\n", RC_CLOSEDAY_TAG, sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    EXEC SQL UPDATE rc_match_log SET status = 'CONFIRMED', updated_at = now()
        WHERE biz_date = :h_bizdate AND status = 'MATCHED';
    if (sqlca.sqlcode < 0) { tpabort(0); return 1; }
    h_conf = sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: bizdate=%s matched=%ld unmatched=%ld gross=%ld confirmed=%ld\n",
           RC_CLOSEDAY_TAG, rec.day, rec.matched, rec.unmatched, rec.gross, h_conf);

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