/* @tier hard @module ac @transform acquire-online */
/*
 * ac_ol_0017.pgc - 매입 온라인 서비스 (AC_OL_0017)  [tier=hard]
 *
 * 매입 세금계산서 연계: 지정 가맹점의 특정 영업일 처리완료(M) 매입 합계를
 * 집계하여 세금계산서를 발행하고, 대상 매입 원장에 세금계산서번호를 반영한다.
 */
#include <stdio.h>
#include <string.h>

#include "txcore.h"
#include "txcore_dbio.h"
#include "acq_util.h"
#include "ac_core.h"

EXEC SQL INCLUDE sqlca;

TX_SERVICE(AC_OL_0017, ctx)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_merch_id[16];
    char h_biz_date[9];
    char h_key[16];
    char h_tax_no[17];
    long h_supply;
    long h_vat;
    long h_supply_amt;
    EXEC SQL END DECLARE SECTION;

    char merch[16], bizdate[9], won[32];
    long tagged = 0;

    tx_log(TX_LOG_INFO, "[AC_OL_0017] 매입 세금계산서 연계 진입");

    if (tx_buf_get(ctx->in, "MERCHID", merch, sizeof(merch)) != TX_OK ||
        tx_buf_get(ctx->in, "BIZDATE", bizdate, sizeof(bizdate)) != TX_OK) {
        tx_log(TX_LOG_ERROR, "[AC_OL_0017] 필수 필드(MERCHID/BIZDATE) 누락");
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    if (!date_is_valid(bizdate)) {
        tx_log(TX_LOG_WARN, "[AC_OL_0017] 영업일 형식 오류 date=%s", bizdate);
        tx_return(ctx, TX_EINVAL, ctx->out);
        return;
    }

    strncpy(h_merch_id, merch, sizeof(h_merch_id) - 1);
    h_merch_id[sizeof(h_merch_id) - 1] = '\0';
    strncpy(h_biz_date, bizdate, sizeof(h_biz_date) - 1);
    h_biz_date[sizeof(h_biz_date) - 1] = '\0';

    if (tx_begin() != TX_OK) {
        tx_log(TX_LOG_ERROR, "[AC_OL_0017] 트랜잭션 시작 실패");
        tx_return(ctx, TX_FAIL, ctx->out);
        return;
    }

    /* 처리완료(M) 매입 합계 집계 (부가세 포함 총액) */
    EXEC SQL SELECT coalesce(sum(amount), 0)
        INTO :h_supply
        FROM ac_ledger
        WHERE merch_id = :h_merch_id
          AND biz_date = :h_biz_date
          AND status   = 'M';

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("SELECT sum ac_ledger(tax)");
        tx_abort();
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    if (h_supply <= 0) {
        tx_log(TX_LOG_WARN, "[AC_OL_0017] 집계대상 없음 merch=%s date=%s",
               merch, bizdate);
        tx_abort();
        tx_return(ctx, TX_ENOENT, ctx->out);
        return;
    }

    /* 부가세 10% 계산, 공급가액 = 매입합계 - 부가세 */
    h_vat        = h_supply / 10;
    h_supply_amt = h_supply - h_vat;

    /* 세금계산서번호 채번: TX + 영업일 + 가맹점번호(6자리) */
    snprintf(h_tax_no, sizeof(h_tax_no), "TX%s%.6s", bizdate, merch);

    EXEC SQL INSERT INTO tax_invoice
        (tax_no, merch_id, biz_date, supply_amt, vat_amt, status)
        VALUES
        (:h_tax_no, :h_merch_id, :h_biz_date, :h_supply_amt, :h_vat, 'I');

    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("INSERT tax_invoice");
        tx_abort();
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    /* 대상 매입 원장 커서 순회, 발행된 세금계산서번호 반영 */
    EXEC SQL DECLARE cur_ac_ol_0017 CURSOR FOR
        SELECT key
        FROM ac_ledger
        WHERE merch_id = :h_merch_id
          AND biz_date = :h_biz_date
          AND status   = 'M';

    EXEC SQL OPEN cur_ac_ol_0017;
    if (sqlca.sqlcode != TX_SQL_OK) {
        TX_DBIO_LOG_ERR("OPEN cur_ac_ol_0017");
        tx_abort();
        tx_return(ctx, TX_EDB, ctx->out);
        return;
    }

    for (;;) {
        EXEC SQL FETCH cur_ac_ol_0017 INTO :h_key;
        if (sqlca.sqlcode == TX_SQL_NOTFOUND)
            break;
        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("FETCH cur_ac_ol_0017");
            EXEC SQL CLOSE cur_ac_ol_0017;
            tx_abort();
            tx_return(ctx, TX_EDB, ctx->out);
            return;
        }

        EXEC SQL UPDATE ac_ledger
            SET tax_no = :h_tax_no
            WHERE key = :h_key;

        if (sqlca.sqlcode != TX_SQL_OK) {
            TX_DBIO_LOG_ERR("UPDATE ac_ledger tax_no");
            EXEC SQL CLOSE cur_ac_ol_0017;
            tx_abort();
            tx_return(ctx, TX_EDB, ctx->out);
            return;
        }
        tagged += sqlca.sqlerrd[2];
    }

    EXEC SQL CLOSE cur_ac_ol_0017;

    tx_commit();

    amount_format_won(h_supply_amt, won, sizeof(won));

    tx_buf_reset(ctx->out);
    tx_buf_sets(ctx->out, "RESPCODE", RESP_OK);
    tx_buf_sets(ctx->out, "TAXNO", h_tax_no);
    tx_buf_setlong(ctx->out, "SUPPLY", h_supply_amt);
    tx_buf_setlong(ctx->out, "VAT", h_vat);
    tx_buf_setlong(ctx->out, "TAGGED", tagged);

    tx_log(TX_LOG_INFO,
           "[AC_OL_0017] 완료 taxno=%s 공급가액=%s(%ld) 부가세=%ld 반영=%ld건",
           h_tax_no, won, h_supply_amt, h_vat, tagged);
    tx_return(ctx, TX_OK, ctx->out);
}
