-- V89: 소개·이관수수료 (referral_commission_rule + referral_commission_ledger)
--      계약을 소개(REFERRAL)하거나 이관(TRANSFER)한 설계사에게 지급하는 수수료.
--      정률(RATE): commission_amount = base_amount × commission_rate
--      정액(FIXED): commission_amount = fixed_amount

-- ============================================================
-- 1. referral_commission_rule — 소개·이관수수료 룰 마스터
-- ============================================================

CREATE TABLE referral_commission_rule (
    rule_id         BIGSERIAL      PRIMARY KEY,
    referral_type   VARCHAR(20)    NOT NULL,
    calc_type       VARCHAR(10)    NOT NULL,
    commission_rate NUMERIC(7,4),
    fixed_amount    NUMERIC(15,2),
    effective_from  DATE           NOT NULL,
    effective_to    DATE,
    created_at      TIMESTAMP      NOT NULL DEFAULT NOW(),
    created_by      BIGINT,
    updated_at      TIMESTAMP,
    CHECK (referral_type IN ('REFERRAL','TRANSFER')),
    CHECK (calc_type IN ('RATE','FIXED')),
    CHECK (commission_rate IS NULL OR (commission_rate >= 0 AND commission_rate <= 1)),
    CHECK (fixed_amount IS NULL OR fixed_amount >= 0)
);

COMMENT ON TABLE  referral_commission_rule                  IS '소개·이관수수료 룰 마스터 — 소개/이관 유형별 수수료율 또는 정액 정의';
COMMENT ON COLUMN referral_commission_rule.rule_id          IS '룰 PK';
COMMENT ON COLUMN referral_commission_rule.referral_type    IS '유형 (REFERRAL=소개 / TRANSFER=이관)';
COMMENT ON COLUMN referral_commission_rule.calc_type        IS '계산방식 (RATE=정률 / FIXED=정액)';
COMMENT ON COLUMN referral_commission_rule.commission_rate  IS '정률 요율 (소수, calc_type=RATE 일 때 사용)';
COMMENT ON COLUMN referral_commission_rule.fixed_amount     IS '정액 금액 (calc_type=FIXED 일 때 사용)';
COMMENT ON COLUMN referral_commission_rule.effective_from   IS '적용 시작일';
COMMENT ON COLUMN referral_commission_rule.effective_to     IS '적용 종료일 (NULL=현재 유효)';

CREATE INDEX idx_rfcr_type_from ON referral_commission_rule(referral_type, effective_from);

-- ============================================================
-- 2. referral_commission_ledger — 소개·이관수수료 원장
-- ============================================================

CREATE TABLE referral_commission_ledger (
    ledger_id          BIGSERIAL      PRIMARY KEY,
    contract_id        BIGINT         NOT NULL REFERENCES contract(contract_id),
    referrer_agent_id  BIGINT         NOT NULL REFERENCES agent(agent_id),
    settle_month       CHAR(6)        NOT NULL,
    referral_type      VARCHAR(20)    NOT NULL,
    base_amount        NUMERIC(15,2)  NOT NULL,
    commission_rate    NUMERIC(7,4),
    commission_amount  NUMERIC(15,2)  NOT NULL,
    status             VARCHAR(20)    NOT NULL DEFAULT 'CALCULATED',
    created_at         TIMESTAMP      NOT NULL DEFAULT NOW(),
    updated_at         TIMESTAMP,
    CHECK (referral_type IN ('REFERRAL','TRANSFER')),
    CHECK (status IN ('CALCULATED','CONFIRMED','CANCELLED')),
    CHECK (base_amount >= 0),
    CHECK (commission_amount >= 0)
);

COMMENT ON TABLE  referral_commission_ledger                    IS '소개·이관수수료 원장 — 소개/이관 설계사에게 지급하는 수수료 발생 이력';
COMMENT ON COLUMN referral_commission_ledger.ledger_id          IS '원장 PK';
COMMENT ON COLUMN referral_commission_ledger.contract_id        IS '대상 계약 FK';
COMMENT ON COLUMN referral_commission_ledger.referrer_agent_id  IS '소개/이관한 설계사 FK';
COMMENT ON COLUMN referral_commission_ledger.settle_month       IS '정산 귀속월 (YYYYMM)';
COMMENT ON COLUMN referral_commission_ledger.referral_type      IS '유형 (REFERRAL=소개 / TRANSFER=이관)';
COMMENT ON COLUMN referral_commission_ledger.base_amount        IS '기준금액 (수수료 또는 보험료)';
COMMENT ON COLUMN referral_commission_ledger.commission_rate    IS '적용 정률 요율 (RATE 방식 시)';
COMMENT ON COLUMN referral_commission_ledger.commission_amount  IS '수수료액 = base×rate (RATE) 또는 fixed_amount (FIXED)';
COMMENT ON COLUMN referral_commission_ledger.status             IS '상태 (CALCULATED/CONFIRMED/CANCELLED)';

CREATE INDEX idx_rfcl_agent_month ON referral_commission_ledger(referrer_agent_id, settle_month);
CREATE INDEX idx_rfcl_contract    ON referral_commission_ledger(contract_id);
