-- 설비 임시이동 필드 추가 및 신고 시스템 연동
-- 실행: docker exec -i tkfb_db mysql -u hyungi -p'your_password' hyungi < db/migrations/20260205002000_add_equipment_move_fields.sql

SET @dbname = DATABASE();

-- ============================================
-- STEP 1: equipments 테이블에 임시이동 필드 추가
-- ============================================

-- current_workplace_id 컬럼 추가
SELECT COUNT(*) INTO @col_exists
FROM information_schema.columns
WHERE table_schema = @dbname AND table_name = 'equipments' AND column_name = 'current_workplace_id';

SET @sql = IF(@col_exists = 0,
    'ALTER TABLE equipments ADD COLUMN current_workplace_id INT UNSIGNED NULL COMMENT ''현재 임시 위치 - 작업장 ID'' AFTER map_height_percent',
    'SELECT ''current_workplace_id already exists''');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- current_map_x_percent 컬럼 추가
SELECT COUNT(*) INTO @col_exists
FROM information_schema.columns
WHERE table_schema = @dbname AND table_name = 'equipments' AND column_name = 'current_map_x_percent';

SET @sql = IF(@col_exists = 0,
    'ALTER TABLE equipments ADD COLUMN current_map_x_percent DECIMAL(5,2) NULL COMMENT ''현재 위치 X%'' AFTER current_workplace_id',
    'SELECT ''current_map_x_percent already exists''');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- current_map_y_percent 컬럼 추가
SELECT COUNT(*) INTO @col_exists
FROM information_schema.columns
WHERE table_schema = @dbname AND table_name = 'equipments' AND column_name = 'current_map_y_percent';

SET @sql = IF(@col_exists = 0,
    'ALTER TABLE equipments ADD COLUMN current_map_y_percent DECIMAL(5,2) NULL COMMENT ''현재 위치 Y%'' AFTER current_map_x_percent',
    'SELECT ''current_map_y_percent already exists''');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- current_map_width_percent 컬럼 추가
SELECT COUNT(*) INTO @col_exists
FROM information_schema.columns
WHERE table_schema = @dbname AND table_name = 'equipments' AND column_name = 'current_map_width_percent';

SET @sql = IF(@col_exists = 0,
    'ALTER TABLE equipments ADD COLUMN current_map_width_percent DECIMAL(5,2) NULL COMMENT ''현재 위치 너비%'' AFTER current_map_y_percent',
    'SELECT ''current_map_width_percent already exists''');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- current_map_height_percent 컬럼 추가
SELECT COUNT(*) INTO @col_exists
FROM information_schema.columns
WHERE table_schema = @dbname AND table_name = 'equipments' AND column_name = 'current_map_height_percent';

SET @sql = IF(@col_exists = 0,
    'ALTER TABLE equipments ADD COLUMN current_map_height_percent DECIMAL(5,2) NULL COMMENT ''현재 위치 높이%'' AFTER current_map_width_percent',
    'SELECT ''current_map_height_percent already exists''');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- is_temporarily_moved 컬럼 추가
SELECT COUNT(*) INTO @col_exists
FROM information_schema.columns
WHERE table_schema = @dbname AND table_name = 'equipments' AND column_name = 'is_temporarily_moved';

SET @sql = IF(@col_exists = 0,
    'ALTER TABLE equipments ADD COLUMN is_temporarily_moved BOOLEAN DEFAULT FALSE COMMENT ''임시 이동 상태'' AFTER current_map_height_percent',
    'SELECT ''is_temporarily_moved already exists''');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- moved_at 컬럼 추가
SELECT COUNT(*) INTO @col_exists
FROM information_schema.columns
WHERE table_schema = @dbname AND table_name = 'equipments' AND column_name = 'moved_at';

SET @sql = IF(@col_exists = 0,
    'ALTER TABLE equipments ADD COLUMN moved_at DATETIME NULL COMMENT ''이동 일시'' AFTER is_temporarily_moved',
    'SELECT ''moved_at already exists''');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- moved_by 컬럼 추가
SELECT COUNT(*) INTO @col_exists
FROM information_schema.columns
WHERE table_schema = @dbname AND table_name = 'equipments' AND column_name = 'moved_by';

SET @sql = IF(@col_exists = 0,
    'ALTER TABLE equipments ADD COLUMN moved_by INT NULL COMMENT ''이동 처리자'' AFTER moved_at',
    'SELECT ''moved_by already exists''');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- Foreign Key: current_workplace_id -> workplaces
SELECT COUNT(*) INTO @fk_exists
FROM information_schema.table_constraints
WHERE table_schema = @dbname AND table_name = 'equipments' AND constraint_name = 'fk_eq_current_workplace';

SET @sql = IF(@fk_exists = 0,
    'ALTER TABLE equipments ADD CONSTRAINT fk_eq_current_workplace FOREIGN KEY (current_workplace_id) REFERENCES workplaces(workplace_id) ON DELETE SET NULL',
    'SELECT ''fk_eq_current_workplace already exists''');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SELECT 'equipments 임시이동 필드 추가 완료' AS status;

-- ============================================
-- STEP 2: work_issue_reports에 equipment_id 필드 추가
-- ============================================

SELECT COUNT(*) INTO @col_exists
FROM information_schema.columns
WHERE table_schema = @dbname AND table_name = 'work_issue_reports' AND column_name = 'equipment_id';

SET @sql = IF(@col_exists = 0,
    'ALTER TABLE work_issue_reports ADD COLUMN equipment_id INT UNSIGNED NULL COMMENT ''관련 설비 ID'' AFTER visit_request_id',
    'SELECT ''equipment_id already exists in work_issue_reports''');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- Foreign Key
SELECT COUNT(*) INTO @fk_exists
FROM information_schema.table_constraints
WHERE table_schema = @dbname AND table_name = 'work_issue_reports' AND constraint_name = 'fk_wir_equipment';

SET @sql = IF(@fk_exists = 0 AND @col_exists = 0,
    'ALTER TABLE work_issue_reports ADD CONSTRAINT fk_wir_equipment FOREIGN KEY (equipment_id) REFERENCES equipments(equipment_id) ON DELETE SET NULL',
    'SELECT ''fk_wir_equipment already exists or column not added''');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- Index
SELECT COUNT(*) INTO @idx_exists
FROM information_schema.statistics
WHERE table_schema = @dbname AND table_name = 'work_issue_reports' AND index_name = 'idx_wir_equipment_id';

SET @sql = IF(@idx_exists = 0 AND @col_exists = 0,
    'ALTER TABLE work_issue_reports ADD INDEX idx_wir_equipment_id (equipment_id)',
    'SELECT ''idx_wir_equipment_id already exists''');
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SELECT 'work_issue_reports equipment_id 추가 완료' AS status;

-- ============================================
-- STEP 3: 설비 수리 카테고리 추가
-- ============================================

INSERT INTO issue_report_categories (category_type, category_name, description, display_order, is_active)
SELECT 'nonconformity', '설비 수리', '설비 고장 및 수리 요청', 10, 1
WHERE NOT EXISTS (
    SELECT 1 FROM issue_report_categories WHERE category_name = '설비 수리'
);

-- 설비 수리 카테고리에 기본 항목 추가
SET @category_id = (SELECT category_id FROM issue_report_categories WHERE category_name = '설비 수리' LIMIT 1);

INSERT INTO issue_report_items (category_id, item_name, description, severity, display_order, is_active)
SELECT @category_id, '기계 고장', '기계 작동 불가 또는 이상', 'high', 1, 1
WHERE @category_id IS NOT NULL AND NOT EXISTS (
    SELECT 1 FROM issue_report_items WHERE category_id = @category_id AND item_name = '기계 고장'
);

INSERT INTO issue_report_items (category_id, item_name, description, severity, display_order, is_active)
SELECT @category_id, '부품 교체 필요', '소모품 또는 부품 교체 필요', 'medium', 2, 1
WHERE @category_id IS NOT NULL AND NOT EXISTS (
    SELECT 1 FROM issue_report_items WHERE category_id = @category_id AND item_name = '부품 교체 필요'
);

INSERT INTO issue_report_items (category_id, item_name, description, severity, display_order, is_active)
SELECT @category_id, '정기 점검 필요', '예방 정비 또는 정기 점검', 'low', 3, 1
WHERE @category_id IS NOT NULL AND NOT EXISTS (
    SELECT 1 FROM issue_report_items WHERE category_id = @category_id AND item_name = '정기 점검 필요'
);

INSERT INTO issue_report_items (category_id, item_name, description, severity, display_order, is_active)
SELECT @category_id, '외부 수리 필요', '전문 업체 수리가 필요한 경우', 'high', 4, 1
WHERE @category_id IS NOT NULL AND NOT EXISTS (
    SELECT 1 FROM issue_report_items WHERE category_id = @category_id AND item_name = '외부 수리 필요'
);

SELECT '설비 수리 카테고리 및 항목 추가 완료' AS status;
