-- ===========================================================================
-- 73-lifecycle.sql : 잔여 패리티 갭 (Wave K) — 온보딩·KYC·3자대사·ISO전문·계정
--   가맹점 심사/언더라이팅, KYC/AML, 3자대사(망·내부·은행), 계정체계(suspense/
--   clearing), 프레젠트먼트 윈도우. 기존 구조 불변(추가만).
-- ===========================================================================

-- ---------------------------------------------------------------------------
-- K-1. 가맹점 온보딩 / 언더라이팅 (심사)
-- ---------------------------------------------------------------------------
CREATE SEQUENCE IF NOT EXISTS mm_app_seq START 300000;
CREATE TABLE IF NOT EXISTS mm_application (
    app_id       BIGINT PRIMARY KEY,
    biz_no       TEXT NOT NULL,               -- 사업자등록번호
    name         TEXT NOT NULL,
    mcc          TEXT NOT NULL,
    rep_name     TEXT NOT NULL DEFAULT '',    -- 대표자
    est_monthly  BIGINT NOT NULL DEFAULT 0,   -- 예상 월매출
    risk_score   INTEGER NOT NULL DEFAULT 0,  -- 언더라이팅 리스크(0~999)
    status       TEXT NOT NULL DEFAULT 'RECEIVED', -- RECEIVED/UNDERWRITING/APPROVED/REJECTED
    reviewer     TEXT,
    decision_at  TIMESTAMPTZ,
    merchant_id  TEXT,                         -- 승인시 발급된 MID
    reject_reason TEXT,
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS ix_app_status ON mm_application(status);

-- ---------------------------------------------------------------------------
-- K-2. KYC / AML 점검
-- ---------------------------------------------------------------------------
CREATE SEQUENCE IF NOT EXISTS mm_kyc_seq START 320000;
CREATE TABLE IF NOT EXISTS mm_kyc (
    kyc_id       BIGINT PRIMARY KEY,
    app_id       BIGINT,
    merchant_id  TEXT,
    check_type   TEXT NOT NULL,               -- IDENTITY/SANCTION/PEP/AML/CREDIT
    result       TEXT NOT NULL DEFAULT 'PASS',-- PASS/FAIL/REVIEW
    score        INTEGER NOT NULL DEFAULT 0,
    detail       TEXT,
    checked_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS ix_kyc_app ON mm_kyc(app_id);

-- ---------------------------------------------------------------------------
-- K-3. 3자 대사 (카드망 정산파일 ↔ 내부원장 ↔ 은행입금)
-- ---------------------------------------------------------------------------
CREATE SEQUENCE IF NOT EXISTS rc_3way_seq START 340000;
CREATE TABLE IF NOT EXISTS rc_3way (
    recon_id     BIGINT PRIMARY KEY,
    biz_date     DATE NOT NULL,
    member_bin   TEXT NOT NULL,
    amt_network  BIGINT NOT NULL DEFAULT 0,   -- 카드망 정산파일 금액
    amt_internal BIGINT NOT NULL DEFAULT 0,   -- 내부 원장 금액
    amt_bank     BIGINT NOT NULL DEFAULT 0,   -- 은행 실입금 금액
    diff_ni      BIGINT NOT NULL DEFAULT 0,   -- 망-내부 차이
    diff_nb      BIGINT NOT NULL DEFAULT 0,   -- 망-은행 차이
    status       TEXT NOT NULL DEFAULT 'MATCHED', -- MATCHED/DIFF/PENDING
    created_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (biz_date, member_bin)
);

-- ---------------------------------------------------------------------------
-- K-4. 총계정 계정과목 (suspense/clearing 분리) — 원장 계정체계
-- ---------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS lg_account (
    acct_code    TEXT PRIMARY KEY,            -- 계정코드
    acct_name    TEXT NOT NULL,
    acct_type    TEXT NOT NULL,              -- ASSET/LIABILITY/REVENUE/EXPENSE/SUSPENSE/CLEARING
    normal_side  TEXT NOT NULL DEFAULT 'D'   -- 정상잔액 방향 D/C
);

-- ---------------------------------------------------------------------------
-- K-5. 프레젠트먼트 윈도우 / interchange downgrade 사유 (기존 테이블 확장)
-- ---------------------------------------------------------------------------
ALTER TABLE cl_presentment ADD COLUMN IF NOT EXISTS window_days INTEGER NOT NULL DEFAULT 1;
ALTER TABLE cl_presentment ADD COLUMN IF NOT EXISTS late_flag BOOLEAN NOT NULL DEFAULT false;
ALTER TABLE st_fee_component ADD COLUMN IF NOT EXISTS downgrade TEXT; -- NULL=정상 등급, 값=강등사유
