-- =====================================================
-- BOM_PART_QTY SEQ 재정렬 마이그레이션 스크립트
-- =====================================================
-- 목적: 전역 시퀀스로 부여된 SEQ를 LEVEL별로 재정렬
-- 작성일: 2025-10-31
-- 설명: 각 BOM_REPORT_OBJID + PARENT_OBJID 그룹 내에서 
--       SEQ를 1, 2, 3... 순차적으로 재정렬
-- =====================================================

-- 1. 백업 테이블 생성 (안전을 위해)
DROP TABLE IF EXISTS bom_part_qty_backup_seq_migration;
CREATE TABLE bom_part_qty_backup_seq_migration AS 
SELECT * FROM bom_part_qty;

-- 백업 확인
SELECT 
    '백업 완료' as status,
    COUNT(*) as backup_count 
FROM bom_part_qty_backup_seq_migration;

-- 2. 현재 SEQ 상태 확인
SELECT 
    bom_report_objid,
    COALESCE(parent_objid, 'ROOT') as parent_level,
    COUNT(*) as part_count,
    MIN(seq) as min_seq,
    MAX(seq) as max_seq,
    ARRAY_AGG(seq ORDER BY seq) as current_seqs
FROM bom_part_qty
WHERE bom_report_objid IS NOT NULL
GROUP BY bom_report_objid, parent_objid
ORDER BY bom_report_objid, parent_objid
LIMIT 20;

-- 3. SEQ 재정렬 실행
-- LEVEL별(PARENT_OBJID별)로 기존 SEQ 순서를 유지하면서 1, 2, 3... 으로 재정렬
WITH numbered_rows AS (
    SELECT 
        objid,
        bom_report_objid,
        parent_objid,
        seq as old_seq,
        ROW_NUMBER() OVER (
            PARTITION BY bom_report_objid, COALESCE(parent_objid, '')
            ORDER BY seq ASC
        ) as new_seq
    FROM bom_part_qty
    WHERE bom_report_objid IS NOT NULL
)
UPDATE bom_part_qty 
SET seq = numbered_rows.new_seq
FROM numbered_rows
WHERE bom_part_qty.objid = numbered_rows.objid;

-- 4. 재정렬 결과 확인
SELECT 
    '재정렬 완료' as status,
    bom_report_objid,
    COALESCE(parent_objid, 'ROOT') as parent_level,
    COUNT(*) as part_count,
    MIN(seq) as min_seq,
    MAX(seq) as max_seq,
    ARRAY_AGG(seq ORDER BY seq) as new_seqs
FROM bom_part_qty
WHERE bom_report_objid IS NOT NULL
GROUP BY bom_report_objid, parent_objid
ORDER BY bom_report_objid, parent_objid
LIMIT 20;

-- 5. 검증: 각 그룹의 SEQ가 1부터 시작하고 연속적인지 확인
WITH seq_check AS (
    SELECT 
        bom_report_objid,
        COALESCE(parent_objid, 'ROOT') as parent_level,
        COUNT(*) as part_count,
        MIN(seq) as min_seq,
        MAX(seq) as max_seq,
        MAX(seq) - MIN(seq) + 1 as expected_count
    FROM bom_part_qty
    WHERE bom_report_objid IS NOT NULL
    GROUP BY bom_report_objid, parent_objid
)
SELECT 
    CASE 
        WHEN COUNT(*) = 0 THEN '✅ 검증 성공: 모든 SEQ가 올바르게 정렬됨'
        ELSE '⚠️ 검증 실패: ' || COUNT(*) || '개 그룹에 문제 있음'
    END as validation_result,
    COUNT(*) as problem_count
FROM seq_check
WHERE min_seq != 1 OR part_count != expected_count;

-- 6. 문제가 있는 그룹 상세 조회 (있다면)
SELECT 
    bom_report_objid,
    COALESCE(parent_objid, 'ROOT') as parent_level,
    COUNT(*) as part_count,
    MIN(seq) as min_seq,
    MAX(seq) as max_seq,
    MAX(seq) - MIN(seq) + 1 as expected_count,
    ARRAY_AGG(seq ORDER BY seq) as actual_seqs
FROM bom_part_qty
WHERE bom_report_objid IS NOT NULL
GROUP BY bom_report_objid, parent_objid
HAVING MIN(seq) != 1 OR COUNT(*) != (MAX(seq) - MIN(seq) + 1)
ORDER BY bom_report_objid, parent_objid;

-- =====================================================
-- 롤백 방법 (문제 발생 시)
-- =====================================================
-- TRUNCATE bom_part_qty;
-- INSERT INTO bom_part_qty SELECT * FROM bom_part_qty_backup_seq_migration;
-- =====================================================

-- 완료 메시지
SELECT '✅ 마이그레이션 완료!' as message;

