/*
 * vl_rule_dbio.pgc - 검증 규칙 조회 + 등록 (libvldbio.a).
 * ECPG functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "vl_dbio.h"

int vldb_get_rule(const char *rule_code, long *threshold_out, char *severity_out)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_thr;
    char h_rule[32], h_sev[8];
    EXEC SQL END DECLARE SECTION;

    strncpy(h_rule, rule_code, sizeof(h_rule) - 1); h_rule[sizeof(h_rule)-1] = 0;

    EXEC SQL SELECT threshold, severity INTO :h_thr, :h_sev
        FROM vl_rule WHERE rule_code = :h_rule AND status = 'ACTIVE';
    if (sqlca.sqlcode < 0 || sqlca.sqlcode == 100) {
        userlog("vldb_get_rule FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    *threshold_out = h_thr;
    strncpy(severity_out, h_sev, 7); severity_out[7] = 0;
    return 0;
}

int vldb_upsert_rule(const char *rule_code, const char *rule_name,
                     long threshold, const char *severity)
{
    EXEC SQL BEGIN DECLARE SECTION;
    long h_thr = threshold;
    char h_rule[32], h_name[64], h_sev[8];
    EXEC SQL END DECLARE SECTION;

    strncpy(h_rule, rule_code, sizeof(h_rule) - 1); h_rule[sizeof(h_rule)-1] = 0;
    strncpy(h_name, rule_name, sizeof(h_name) - 1); h_name[sizeof(h_name)-1] = 0;
    strncpy(h_sev,  severity,  sizeof(h_sev) - 1);  h_sev[sizeof(h_sev)-1]   = 0;

    EXEC SQL INSERT INTO vl_rule (rule_code, rule_name, threshold, severity)
        VALUES (:h_rule, :h_name, :h_thr, :h_sev)
        ON CONFLICT (rule_code) DO UPDATE
        SET rule_name = EXCLUDED.rule_name, threshold = EXCLUDED.threshold,
            severity = EXCLUDED.severity, updated_at = now();
    if (sqlca.sqlcode < 0) {
        userlog("vldb_upsert_rule FAIL [%d] %s", sqlca.sqlcode, sqlca.sqlerrm.sqlerrmc);
        return -1;
    }
    return 0;
}
