/*
 * ac_wht_batch.pgc - ac 원천징수 배치 (커서 + XA).
 *
 * Cursors over settled purchases of a biz_date that have no withholding row yet
 * and inserts a 22% withholding record (via dbio) for each, all under ONE global
 * XA transaction. Usage: ac_wht_batch [YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "ac_dbio.h"
#include "acq_common.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_pid, h_fee;
    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 whc CURSOR FOR
        SELECT p.purchase_id, p.fee FROM purchase p
        WHERE p.biz_date = :h_bizdate
          AND NOT EXISTS (SELECT 1 FROM ac_wht w WHERE w.purchase_id = p.purchase_id)
        ORDER BY p.purchase_id;
    EXEC SQL OPEN whc;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "OPEN FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }

    for (;;) {
        EXEC SQL FETCH whc INTO :h_pid, :h_fee;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { fprintf(stderr, "FETCH FAIL [%d] %s\n", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); EXEC SQL CLOSE whc; tpabort(0); return 1; }
        if (acdb_insert_wht(h_pid, acq_wht_amt(h_fee, 2200), bizdate) < 0) {
            EXEC SQL CLOSE whc; tpabort(0); return 1;
        }
        rows++;
    }
    EXEC SQL CLOSE whc;

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

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