-- ===========================================================================
-- 71-econ2.sql : 매입사 경제모델 2차 고도화 (갭분석 2·3순위)
--   ① interchange qualification 심화: MCC(업종)별 요율 tier
--   ② ISO 8583 클리어링 메시지 클래스 (presentment/chargeback/recon/fee/reject)
--   ③ 이중메시지 vs 단일메시지 구분
-- ===========================================================================

-- ---------------------------------------------------------------------------
-- 1. 가맹점 → MCC 매핑 (실제 4자리 ISO MCC).
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS mm_merch_mcc (
    merchant_id TEXT PRIMARY KEY,
    mcc         TEXT NOT NULL
);

-- ---------------------------------------------------------------------------
-- 2. ISO 8583 클리어링 메시지 (승인전문 mg_msg_log 과 별개인 클리어링 단계).
--    msg_class: 실제 ISO 8583 클리어링 기능 (Berlin Group).
--    msg_type : DUAL(신용/서명-승인과 클리어링 분리) / SINGLE(PIN/직불-통합).
-- ---------------------------------------------------------------------------
CREATE SEQUENCE IF NOT EXISTS mg_clearing_seq START 500000;
CREATE TABLE IF NOT EXISTS mg_clearing (
    clr_id      BIGINT PRIMARY KEY,
    purchase_id BIGINT,
    scheme      TEXT NOT NULL DEFAULT 'BC',
    msg_class   TEXT NOT NULL,                  -- PRESENTMENT/CHARGEBACK/REPRESENT/RECONCILE/FEE_COLLECT/FILE_REJECT
    mti         TEXT NOT NULL,                  -- 1240(1st present)/1442(chargeback)/1740(fee)/1500(recon)/1644(file action)
    msg_type    TEXT NOT NULL DEFAULT 'DUAL',   -- DUAL / SINGLE
    amount      BIGINT NOT NULL DEFAULT 0,
    biz_date    DATE NOT NULL,
    status      TEXT NOT NULL DEFAULT 'ACCEPTED', -- ACCEPTED/REJECTED
    reject_code TEXT,                            -- 파일/메시지 거부 사유
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS ix_clearing_pid ON mg_clearing(purchase_id);
CREATE INDEX IF NOT EXISTS ix_clearing_class ON mg_clearing(msg_class);
