-- vl 모듈 (정합성검증/validation) 상세 스키마
-- 검증 규칙 / 의심거래(suspect) / 검증 로그. Loaded on first boot.

-- ---------------------------------------------------------------------------
-- 검증 규칙 마스터 (vl_rule)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS vl_rule (
    rule_code    TEXT PRIMARY KEY,
    rule_name    TEXT NOT NULL DEFAULT '',
    threshold    BIGINT NOT NULL DEFAULT 0,     -- 규칙별 임계값 (금액/건수 등)
    severity     TEXT NOT NULL DEFAULT 'WARN',  -- INFO / WARN / ERROR / CRIT
    status       TEXT NOT NULL DEFAULT 'ACTIVE',
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- ---------------------------------------------------------------------------
-- 의심거래 (vl_suspect) - 검증 실패/이상 거래 적재
-- ---------------------------------------------------------------------------
CREATE SEQUENCE IF NOT EXISTS vl_suspect_seq;
CREATE TABLE IF NOT EXISTS vl_suspect (
    suspect_id   BIGINT PRIMARY KEY,
    purchase_id  BIGINT NOT NULL DEFAULT 0,
    rule_code    TEXT NOT NULL,
    severity     TEXT NOT NULL DEFAULT 'WARN',
    detail       TEXT NOT NULL DEFAULT '',
    status       TEXT NOT NULL DEFAULT 'OPEN',  -- OPEN / CONFIRMED / CLOSED
    biz_date     DATE NOT NULL,
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- ---------------------------------------------------------------------------
-- 검증 로그 (vl_check_log) - 모든 검증 서비스 호출 기록
-- ---------------------------------------------------------------------------
CREATE SEQUENCE IF NOT EXISTS vl_checklog_seq;
CREATE TABLE IF NOT EXISTS vl_check_log (
    log_id       BIGINT PRIMARY KEY,
    check_type   TEXT NOT NULL,                 -- 서비스명 (VL_SALES 등)
    target_id    BIGINT NOT NULL DEFAULT 0,     -- 검증 대상 (purchase_id 등)
    result_code  BIGINT NOT NULL DEFAULT 0,     -- 0=정상, >0=검증 실패코드
    detail       TEXT NOT NULL DEFAULT '',
    biz_date     DATE NOT NULL,
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Seed 기본 검증 규칙
INSERT INTO vl_rule (rule_code, rule_name, threshold, severity) VALUES
    ('AMT_MAX',   '최대금액 초과',   50000000, 'ERROR'),
    ('AMT_ZERO',  '0원/음수 금액',   0,        'ERROR'),
    ('DUP_TXN',   '중복 매입',       1,        'WARN'),
    ('LIMIT_OVR', '일한도 초과',     0,        'WARN'),
    ('LEDGER_MIS','원장 불일치',     0,        'CRIT')
ON CONFLICT (rule_code) DO NOTHING;
