/*
 * st_weekly_batch.pgc - 주간 정산주기 배치 (7일 윈도 집합 INSERT..SELECT + XA).
 * 주 종료일 기준 직전 7일 정산 net 을 가맹점별 GROUP BY/HAVING 으로 합산해
 * 주 1회 지급(SCHEDULED)을 일괄 생성한다. 사용법: st_weekly_batch [주종료일 YYYY-MM-DD]
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <atmi.h>
#include "st_dbio.h"
#include "st_weekly_batch.h"

int main(int argc, char **argv)
{
    const char *bizdate = (argc > 1) ? argv[1] : "2026-07-19";
    st_weekly_rec_t rec;
    rec.merchants = 0;
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[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 INSERT INTO st_payment (pay_id, merchant_id, net_amount, pay_date, status, biz_date)
        SELECT nextval('st_pay_seq'), merchant_id, sum(net), :h_bizdate::date + 1, 'SCHEDULED', :h_bizdate
        FROM settlement
        WHERE status <> 'CANCELLED'
          AND biz_date BETWEEN :h_bizdate::date - 6 AND :h_bizdate::date
        GROUP BY merchant_id
        HAVING sum(net) > 0;
    if (sqlca.sqlcode < 0) { fprintf(stderr, "%s FAIL [%d] %s\n", ST_WEEKLY_TAG, sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); tpabort(0); return 1; }
    rec.merchants = (long) sqlca.sqlerrd[2];

    if (tpcommit(0) < 0) { fprintf(stderr, "tpcommit FAIL: %s\n", tpstrerror(tperrno)); tpabort(0); return 1; }
    printf(">>> %s COMMIT: week_end=%s weekly_payments=%ld\n", ST_WEEKLY_TAG, bizdate, rec.merchants);

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