-- mm 모듈 (마스터/master) 상세 스키마
-- 가맹점 확장원장 / 수수료율 / BIN / 공통코드 / 한도 / 발급사 / 단말 / MCC /
-- 공휴일 / 환율 마스터 + 이력. Loaded on first boot (docker-entrypoint-initdb.d).

-- ---------------------------------------------------------------------------
-- 가맹점 확장 마스터 (mm_merchant_ext) - base merchant를 보강하는 마스터 원장
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS mm_merchant_ext (
    merchant_id  TEXT PRIMARY KEY,
    name         TEXT NOT NULL,
    biz_reg_no   TEXT NOT NULL DEFAULT '',      -- 사업자등록번호
    grade        TEXT NOT NULL DEFAULT 'C',     -- 가맹점 등급 (S/A/B/C)
    settle_acct  TEXT NOT NULL DEFAULT '',      -- 정산 계좌
    mcc          TEXT NOT NULL DEFAULT '0000',  -- 업종코드
    status       TEXT NOT NULL DEFAULT 'ACTIVE',-- ACTIVE / HOLD / DELETED
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- 가맹점 마스터 변경 이력
CREATE SEQUENCE IF NOT EXISTS mm_merch_hist_seq;
CREATE TABLE IF NOT EXISTS mm_merch_hist (
    hist_id       BIGINT PRIMARY KEY,
    merchant_id   TEXT NOT NULL,
    action        TEXT NOT NULL,                -- REG / UPD / DEL / STATUS / GRADE / ACCT
    before_val    TEXT NOT NULL DEFAULT '',
    after_val     TEXT NOT NULL DEFAULT '',
    memo          TEXT NOT NULL DEFAULT '',
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- ---------------------------------------------------------------------------
-- 수수료율 마스터 (mm_fee_rate) + 이력
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS mm_fee_rate (
    merchant_id  TEXT NOT NULL,
    card_type    TEXT NOT NULL DEFAULT 'CREDIT',-- CREDIT / CHECK / PREPAID
    rate_bps     BIGINT NOT NULL DEFAULT 25,    -- basis points
    eff_date     DATE NOT NULL DEFAULT current_date,
    updated_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (merchant_id, card_type)
);

CREATE SEQUENCE IF NOT EXISTS mm_feerate_hist_seq;
CREATE TABLE IF NOT EXISTS mm_fee_rate_hist (
    hist_id      BIGINT PRIMARY KEY,
    merchant_id  TEXT NOT NULL,
    card_type    TEXT NOT NULL,
    rate_bps     BIGINT NOT NULL,
    eff_date     DATE NOT NULL,
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- ---------------------------------------------------------------------------
-- BIN 마스터 (mm_bin)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS mm_bin (
    bin          TEXT PRIMARY KEY,              -- 6-8 digit BIN
    issuer_cd    TEXT NOT NULL DEFAULT 'UNKNOWN',
    card_brand   TEXT NOT NULL DEFAULT 'LOCAL', -- VISA / MASTER / LOCAL
    card_type    TEXT NOT NULL DEFAULT 'CREDIT',
    status       TEXT NOT NULL DEFAULT 'ACTIVE',
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- ---------------------------------------------------------------------------
-- 공통코드 마스터 (mm_code)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS mm_code (
    code_group   TEXT NOT NULL,
    code         TEXT NOT NULL,
    code_name    TEXT NOT NULL DEFAULT '',
    sort_order   INTEGER NOT NULL DEFAULT 0,
    status       TEXT NOT NULL DEFAULT 'ACTIVE',
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (code_group, code)
);

-- ---------------------------------------------------------------------------
-- 가맹점 한도 마스터 (mm_limit)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS mm_limit (
    merchant_id   TEXT PRIMARY KEY,
    daily_limit   BIGINT NOT NULL DEFAULT 100000000,
    monthly_limit BIGINT NOT NULL DEFAULT 3000000000,
    per_txn_limit BIGINT NOT NULL DEFAULT 10000000,
    updated_at    TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- ---------------------------------------------------------------------------
-- 발급사 마스터 (mm_issuer)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS mm_issuer (
    issuer_cd    TEXT PRIMARY KEY,
    issuer_name  TEXT NOT NULL DEFAULT '',
    country      TEXT NOT NULL DEFAULT 'KR',
    status       TEXT NOT NULL DEFAULT 'ACTIVE',
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- ---------------------------------------------------------------------------
-- 단말 마스터 (mm_terminal)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS mm_terminal (
    terminal_id  TEXT PRIMARY KEY,
    merchant_id  TEXT NOT NULL,
    model        TEXT NOT NULL DEFAULT 'STD',
    status       TEXT NOT NULL DEFAULT 'ACTIVE',
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- ---------------------------------------------------------------------------
-- MCC 업종 마스터 (mm_mcc)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS mm_mcc (
    mcc          TEXT PRIMARY KEY,
    mcc_name     TEXT NOT NULL DEFAULT '',
    risk_level   INTEGER NOT NULL DEFAULT 1
);

-- ---------------------------------------------------------------------------
-- 공휴일 마스터 (mm_holiday)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS mm_holiday (
    holiday_date DATE PRIMARY KEY,
    holiday_name TEXT NOT NULL DEFAULT '',
    nation       TEXT NOT NULL DEFAULT 'KR'
);

-- ---------------------------------------------------------------------------
-- 환율 마스터 (mm_fx_rate)
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS mm_fx_rate (
    ccy          TEXT PRIMARY KEY,
    rate_bps     BIGINT NOT NULL DEFAULT 100,   -- KRW per unit, in bps of 100
    base_date    DATE NOT NULL DEFAULT current_date,
    updated_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- ---------------------------------------------------------------------------
-- 등급 통계 (mm_grade_stat) - mm_stat_batch가 채움
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS mm_grade_stat (
    stat_date    DATE NOT NULL,
    grade        TEXT NOT NULL,
    merch_cnt    BIGINT NOT NULL DEFAULT 0,
    updated_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (stat_date, grade)
);

-- Seed 몇 개 마스터 (테스트/데모용)
INSERT INTO mm_code (code_group, code, code_name, sort_order) VALUES
    ('CARD_TYPE', 'CREDIT', '신용카드', 1),
    ('CARD_TYPE', 'CHECK',  '체크카드', 2),
    ('GRADE',     'S',      '최우수', 1),
    ('GRADE',     'A',      '우수',   2)
ON CONFLICT (code_group, code) DO NOTHING;

INSERT INTO mm_issuer (issuer_cd, issuer_name, country) VALUES
    ('BC',   'BC카드',    'KR'),
    ('SHC',  '신한카드',  'KR')
ON CONFLICT (issuer_cd) DO NOTHING;
