/*
 * lg_worst_acct_dbio.pgc - lg 모듈 DB 접근 함수 (lg_worst_acct_dbio), archived into liblgdbio.a.
 * 당일 차대 불일치 절대값이 가장 큰 계정과목과 그 차액을 찾는다.
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "lg_worst_acct_dbio.h"

/* GROUP BY + CASE + abs + ORDER LIMIT: 최대 불균형 계정. */
int lgqdb_worst_acct(const char *bizdate, char *acct_out, long *diff_out)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_bizdate[16], h_acct[32];
    long h_diff = 0;
    EXEC SQL END DECLARE SECTION;
    strncpy(h_bizdate, bizdate, sizeof(h_bizdate)-1); h_bizdate[sizeof(h_bizdate)-1] = 0;
    EXEC SQL SELECT acct, abs(coalesce(sum(CASE WHEN dc='D' THEN amount ELSE 0 END),0)
                            - coalesce(sum(CASE WHEN dc='C' THEN amount ELSE 0 END),0)) AS d
        INTO :h_acct, :h_diff FROM lg_ledger_line WHERE biz_date = :h_bizdate
        GROUP BY acct ORDER BY d DESC LIMIT 1;
    if (sqlca.sqlcode == 100) { acct_out[0] = 0; *diff_out = 0; return 0; }
    if (sqlca.sqlcode < 0) { userlog("lgqdb_worst_acct FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc); return -1; }
    strcpy(acct_out, h_acct); *diff_out = h_diff;
    return 0;
}
