-- =================================================================
-- V022: DEPT_MANAGERS 테이블 (다중 결재/부서/조직장 매핑)
-- =================================================================
-- 기존 DEPT_INFO.APPROVAL_MANAGER / DEPT_MANAGER 단일 컬럼을 매핑 테이블로 다중화.
-- role: 'approval' | 'dept' | 'org_leader'. 부서 삭제(hard) 시 CASCADE 로 정리.
-- 멱등: IF NOT EXISTS 로 재실행 안전.

CREATE TABLE IF NOT EXISTS DEPT_MANAGERS (
    DEPT_CODE   VARCHAR(1024) NOT NULL,
    USER_ID     VARCHAR(50)   NOT NULL,
    ROLE        VARCHAR(20)   NOT NULL,
    SORT_ORDER  INTEGER       NOT NULL DEFAULT 1,
    CREATED_AT  TIMESTAMP     NOT NULL DEFAULT NOW(),
    PRIMARY KEY (DEPT_CODE, USER_ID, ROLE),
    CONSTRAINT chk_dept_managers_role
        CHECK (ROLE IN ('approval', 'dept', 'org_leader')),
    CONSTRAINT fk_dept_managers_dept
        FOREIGN KEY (DEPT_CODE) REFERENCES DEPT_INFO(DEPT_CODE) ON DELETE CASCADE
);

CREATE INDEX IF NOT EXISTS idx_dept_managers_role
    ON DEPT_MANAGERS (DEPT_CODE, ROLE, SORT_ORDER);
