-- PIPE_DETAILS 테이블 간소화 스크립트
-- 2025.01.17 - 실무 중심 구조 개선

-- 기존 테이블 백업
CREATE TABLE IF NOT EXISTS pipe_details_backup AS SELECT * FROM pipe_details;

-- 새로운 간소화된 테이블 생성
DROP TABLE IF EXISTS pipe_details_new;
CREATE TABLE pipe_details_new (
    id SERIAL PRIMARY KEY,
    material_id INTEGER NOT NULL,
    file_id INTEGER NOT NULL,
    
    -- 핵심 PIPE 정보 (실무 필수)
    outer_diameter VARCHAR(20),           -- main_nom 기반 외경 정보
    schedule VARCHAR(10),                 -- SCH 40, SCH 80 등
    material_spec VARCHAR(100),           -- 단일 재질 정보 (ASTM A106 GR B)
    manufacturing_method VARCHAR(20),     -- SEAMLESS, WELDED, CAST
    end_preparation VARCHAR(20),          -- POE, BOE, PEE, BEE 등
    length_mm DECIMAL(10,2),              -- 길이 (mm)
    
    -- 추가 정보 (cutting plan 용)
    area_number VARCHAR(10),              -- 에리어 번호 (#01, #02)
    spool_number VARCHAR(10),             -- 스풀 번호 (A, B, C)
    drawing_number VARCHAR(50),           -- 도면 번호
    
    -- 메타 정보
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    
    -- 외래키
    FOREIGN KEY (material_id) REFERENCES materials(id) ON DELETE CASCADE,
    FOREIGN KEY (file_id) REFERENCES files(id) ON DELETE CASCADE
);

-- 인덱스 추가 (성능)
CREATE INDEX IF NOT EXISTS idx_pipe_details_material_id ON pipe_details_new(material_id);
CREATE INDEX IF NOT EXISTS idx_pipe_details_file_id ON pipe_details_new(file_id);
CREATE INDEX IF NOT EXISTS idx_pipe_details_outer_diameter ON pipe_details_new(outer_diameter);
CREATE INDEX IF NOT EXISTS idx_pipe_details_schedule ON pipe_details_new(schedule);

-- 기존 데이터 마이그레이션 (가능한 것만)
INSERT INTO pipe_details_new (
    material_id, file_id, outer_diameter, schedule, material_spec, 
    manufacturing_method, length_mm
)
SELECT 
    material_id, 
    file_id,
    nominal_size as outer_diameter,  -- nominal_size를 outer_diameter로
    schedule,
    COALESCE(material_standard, material_grade, material_type) as material_spec,  -- 중복 필드 통합
    manufacturing_method,
    length_mm
FROM pipe_details
WHERE material_id IS NOT NULL;

-- 백업 테이블로 기존 테이블 교체
DROP TABLE IF EXISTS pipe_details;
ALTER TABLE pipe_details_new RENAME TO pipe_details;

-- 코멘트 추가
COMMENT ON TABLE pipe_details IS '간소화된 PIPE 상세 정보 - 실무 중심 구조';
COMMENT ON COLUMN pipe_details.outer_diameter IS '외경 정보 (main_nom에서 추출, 예: 4", 150A)';
COMMENT ON COLUMN pipe_details.material_spec IS '통합 재질 정보 (예: ASTM A106 GR B)';
COMMENT ON COLUMN pipe_details.end_preparation IS '끝단 가공 (POE-BOE, PEE, BEE 등)';
COMMENT ON COLUMN pipe_details.area_number IS '에리어 번호 (cutting plan용)';
COMMENT ON COLUMN pipe_details.spool_number IS '스풀 번호 (cutting plan용)'; 