-- ============================================================================
-- V002: 권한 트리 + 권한 매트릭스 (wing 패턴)
-- ============================================================================

-- ----------------------------------------------------------------------------
-- 리소스 트리 (메뉴/탭/패널 계층 구조)
-- ----------------------------------------------------------------------------
CREATE TABLE kcg.auth_perm_tree (
    rsrc_cd         VARCHAR(100) PRIMARY KEY,
    parent_cd       VARCHAR(100) REFERENCES kcg.auth_perm_tree(rsrc_cd) ON DELETE CASCADE,
    rsrc_nm         VARCHAR(100) NOT NULL,
    rsrc_desc       TEXT,
    icon            VARCHAR(50),
    rsrc_level      INT NOT NULL DEFAULT 0,             -- 0=tab(권한그룹), 1=subtab/패널, 2+=중첩
    sort_ord        INT NOT NULL DEFAULT 0,
    use_yn          VARCHAR(1) NOT NULL DEFAULT 'Y',
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX idx_perm_tree_parent ON kcg.auth_perm_tree(parent_cd);
CREATE INDEX idx_perm_tree_level ON kcg.auth_perm_tree(rsrc_level, sort_ord);

COMMENT ON TABLE kcg.auth_perm_tree IS '리소스 트리 (좌측 탭=권한그룹, 자식=패널/액션)';
COMMENT ON COLUMN kcg.auth_perm_tree.rsrc_cd IS '리소스 코드 (예: detection, detection:gear-detection)';

-- ----------------------------------------------------------------------------
-- 권한 매트릭스 (역할 × 리소스 × 오퍼레이션)
-- ----------------------------------------------------------------------------
CREATE TABLE kcg.auth_perm (
    perm_sn         BIGSERIAL PRIMARY KEY,
    role_sn         BIGINT NOT NULL REFERENCES kcg.auth_role(role_sn) ON DELETE CASCADE,
    rsrc_cd         VARCHAR(100) NOT NULL REFERENCES kcg.auth_perm_tree(rsrc_cd) ON DELETE CASCADE,
    oper_cd         VARCHAR(20) NOT NULL,               -- READ, CREATE, UPDATE, DELETE, EXPORT, MANAGE
    grant_yn        VARCHAR(1) NOT NULL,                   -- Y(허용), N(명시적 거부)
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_by      UUID,
    UNIQUE(role_sn, rsrc_cd, oper_cd)
);

CREATE INDEX idx_perm_role ON kcg.auth_perm(role_sn);
CREATE INDEX idx_perm_rsrc ON kcg.auth_perm(rsrc_cd);

COMMENT ON TABLE kcg.auth_perm IS '권한 매트릭스 (명시적 권한만 저장, 미저장 시 트리 상속)';

-- ----------------------------------------------------------------------------
-- 시스템 설정 (메뉴 구성, 자동 승인 등 JSON)
-- ----------------------------------------------------------------------------
CREATE TABLE kcg.auth_setting (
    setting_key     VARCHAR(50) PRIMARY KEY,
    setting_val     JSONB NOT NULL,
    description     TEXT,
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT now(),
    updated_by      UUID
);

COMMENT ON TABLE kcg.auth_setting IS '시스템 설정 (메뉴 구성, 자동승인, 정책 등)';
