-- V10: 메뉴 / 권한 / 역할

CREATE TABLE menu (
    menu_id         SERIAL PRIMARY KEY,
    parent_menu_id  BIGINT REFERENCES menu(menu_id),
    menu_code       VARCHAR(50)  NOT NULL UNIQUE,
    menu_name       VARCHAR(100) NOT NULL,
    menu_type       VARCHAR(20)  NOT NULL,            -- DIRECTORY / PAGE / LINK
    menu_path       VARCHAR(200),
    menu_icon       VARCHAR(50),
    component_path  VARCHAR(200),
    menu_level      INT          NOT NULL,
    sort_order      INT          NOT NULL DEFAULT 0,
    is_visible      CHAR(1)      NOT NULL DEFAULT 'Y',
    is_active       CHAR(1)      NOT NULL DEFAULT 'Y',
    description     VARCHAR(300)
);
CREATE INDEX idx_menu_parent ON menu(parent_menu_id, sort_order);

CREATE TABLE menu_permission (
    perm_id     SERIAL PRIMARY KEY,
    menu_id     BIGINT      NOT NULL REFERENCES menu(menu_id),
    perm_code   VARCHAR(20) NOT NULL,                -- READ / CREATE / UPDATE / DELETE / APPROVE / EXPORT / PRINT
    perm_name   VARCHAR(50) NOT NULL,
    sort_order  INT         NOT NULL DEFAULT 0,
    UNIQUE (menu_id, perm_code)
);

CREATE TABLE role (
    role_id     SERIAL PRIMARY KEY,
    role_code   VARCHAR(50)  NOT NULL UNIQUE,
    role_name   VARCHAR(100) NOT NULL,
    role_desc   VARCHAR(300),
    role_level  INT          NOT NULL DEFAULT 0,
    is_system   CHAR(1)      NOT NULL DEFAULT 'N',
    is_active   CHAR(1)      NOT NULL DEFAULT 'Y'
);

CREATE TABLE role_menu_permission (
    rmp_id      SERIAL PRIMARY KEY,
    role_id     BIGINT      NOT NULL REFERENCES role(role_id),
    menu_id     BIGINT      NOT NULL REFERENCES menu(menu_id),
    perm_code   VARCHAR(20) NOT NULL,
    is_granted  CHAR(1)     NOT NULL DEFAULT 'Y',
    UNIQUE (role_id, menu_id, perm_code)
);
CREATE INDEX idx_rmp_role ON role_menu_permission(role_id);

CREATE TABLE user_role (
    ur_id    SERIAL PRIMARY KEY,
    user_id  BIGINT NOT NULL REFERENCES users(user_id),
    role_id  BIGINT NOT NULL REFERENCES role(role_id),
    UNIQUE (user_id, role_id)
);
