-- ===================================================================
-- TK Factory Services - SSO 통합 유저 마이그레이션
-- ===================================================================
-- 이 스크립트는 MariaDB 초기 구동 시 자동 실행됩니다.
-- 기존 DB에 적용할 때는 수동으로 실행하세요.
-- ===================================================================

-- 1. SSO 통합 유저 테이블 생성
CREATE TABLE IF NOT EXISTS sso_users (
    user_id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    password_hash VARCHAR(255) NOT NULL,
    name VARCHAR(100),
    department VARCHAR(50),
    role ENUM('system','admin','support_team','leader','user') DEFAULT 'user',
    system1_access BOOLEAN DEFAULT TRUE,
    system2_access BOOLEAN DEFAULT TRUE,
    system3_access BOOLEAN DEFAULT TRUE,
    is_active BOOLEAN DEFAULT TRUE,
    last_login DATETIME NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 2. work_issue_reports 테이블에 M-Project 연동 컬럼 추가
-- (테이블이 존재하는 경우에만 실행)
-- ALTER TABLE은 IF NOT EXISTS를 지원하지 않으므로 프로시저 사용
DELIMITER //
CREATE PROCEDURE IF NOT EXISTS add_mproject_columns()
BEGIN
    -- work_issue_reports 테이블 존재 확인
    IF EXISTS (SELECT 1 FROM information_schema.tables
               WHERE table_schema = DATABASE()
               AND table_name = 'work_issue_reports') THEN

        -- m_project_issue_id 컬럼 추가
        IF NOT EXISTS (SELECT 1 FROM information_schema.columns
                       WHERE table_schema = DATABASE()
                       AND table_name = 'work_issue_reports'
                       AND column_name = 'm_project_issue_id') THEN
            ALTER TABLE work_issue_reports
                ADD COLUMN m_project_issue_id INT NULL;
        END IF;

        -- m_project_sync_status 컬럼 추가
        IF NOT EXISTS (SELECT 1 FROM information_schema.columns
                       WHERE table_schema = DATABASE()
                       AND table_name = 'work_issue_reports'
                       AND column_name = 'm_project_sync_status') THEN
            ALTER TABLE work_issue_reports
                ADD COLUMN m_project_sync_status ENUM('pending','synced','failed','not_applicable')
                    DEFAULT 'not_applicable';
        END IF;

        -- m_project_synced_at 컬럼 추가
        IF NOT EXISTS (SELECT 1 FROM information_schema.columns
                       WHERE table_schema = DATABASE()
                       AND table_name = 'work_issue_reports'
                       AND column_name = 'm_project_synced_at') THEN
            ALTER TABLE work_issue_reports
                ADD COLUMN m_project_synced_at DATETIME NULL;
        END IF;
    END IF;
END //
DELIMITER ;

CALL add_mproject_columns();
DROP PROCEDURE IF EXISTS add_mproject_columns;

-- 3. 기존 users 테이블에서 SSO 유저 마이그레이션 (중복 무시)
-- (TK-FB-Project의 users 테이블이 있는 경우)
DELIMITER //
CREATE PROCEDURE IF NOT EXISTS migrate_existing_users()
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.tables
               WHERE table_schema = DATABASE()
               AND table_name = 'users') THEN
        INSERT IGNORE INTO sso_users (username, password_hash, name, department, role, is_active)
        SELECT
            username,
            password,
            name,
            department,
            CASE
                WHEN access_level = 'system' THEN 'system'
                WHEN access_level = 'admin' THEN 'admin'
                WHEN access_level = 'support_team' THEN 'support_team'
                WHEN access_level = 'group_leader' THEN 'leader'
                ELSE 'user'
            END AS role,
            COALESCE(is_active, TRUE)
        FROM users
        WHERE username IS NOT NULL;
    END IF;
END //
DELIMITER ;

CALL migrate_existing_users();
DROP PROCEDURE IF EXISTS migrate_existing_users;
