-- ============================================
-- 권한 관리 시스템 테이블 생성
-- 작성일: 2025-01-10
-- ============================================

-- 1. 권한 마스터 테이블
CREATE TABLE IF NOT EXISTS wr_role (
    role_id SERIAL PRIMARY KEY,
    role_code VARCHAR(50) NOT NULL UNIQUE,        -- ROLE_ADMIN, ROLE_MANAGER, ROLE_USER
    role_name VARCHAR(100) NOT NULL,              -- 관리자, 매니저, 일반사용자
    role_description TEXT,                        -- 권한 설명
    is_internal_ip_only BOOLEAN DEFAULT false,    -- 내부IP 제한 여부
    sort_order INTEGER DEFAULT 0,                 -- 정렬 순서
    is_active BOOLEAN DEFAULT true,               -- 활성화 여부
    created_at TIMESTAMP DEFAULT NOW(),
    updated_at TIMESTAMP DEFAULT NOW()
);

-- 2. 사용자-권한 매핑 테이블
CREATE TABLE IF NOT EXISTS wr_employee_role (
    employee_role_id SERIAL PRIMARY KEY,
    employee_id INTEGER NOT NULL REFERENCES wr_employee_info(employee_id) ON DELETE CASCADE,
    role_id INTEGER NOT NULL REFERENCES wr_role(role_id) ON DELETE CASCADE,
    created_at TIMESTAMP DEFAULT NOW(),
    UNIQUE(employee_id, role_id)
);

-- 인덱스 생성
CREATE INDEX IF NOT EXISTS idx_employee_role_employee ON wr_employee_role(employee_id);
CREATE INDEX IF NOT EXISTS idx_employee_role_role ON wr_employee_role(role_id);
CREATE INDEX IF NOT EXISTS idx_role_code ON wr_role(role_code);

-- ============================================
-- 기본 권한 데이터 INSERT
-- ============================================
INSERT INTO wr_role (role_code, role_name, role_description, sort_order) VALUES
('ROLE_ADMIN', '관리자', '시스템 전체 관리 권한', 1),
('ROLE_MANAGER', '매니저', '취합보고서 등 관리 기능', 2),
('ROLE_USER', '일반사용자', '기본 기능 (주간보고 작성/조회)', 3)
ON CONFLICT (role_code) DO NOTHING;

-- ============================================
-- 기존 관리자 계정에 ROLE_ADMIN 부여
-- ============================================
INSERT INTO wr_employee_role (employee_id, role_id)
SELECT e.employee_id, r.role_id
FROM wr_employee_info e, wr_role r
WHERE e.employee_email = 'coziny@gmail.com'
  AND r.role_code = 'ROLE_ADMIN'
ON CONFLICT (employee_id, role_id) DO NOTHING;

-- ============================================
-- 확인 쿼리
-- ============================================
-- SELECT * FROM wr_role ORDER BY sort_order;
-- SELECT e.employee_name, e.employee_email, r.role_code, r.role_name
-- FROM wr_employee_info e
-- JOIN wr_employee_role er ON e.employee_id = er.employee_id
-- JOIN wr_role r ON er.role_id = r.role_id;
