-- 엑셀 내보내기 이력 및 구매 상태 관리 테이블

-- 1. 엑셀 내보내기 이력 테이블
CREATE TABLE IF NOT EXISTS excel_export_history (
    export_id SERIAL PRIMARY KEY,
    file_id INTEGER REFERENCES files(id) ON DELETE CASCADE,
    job_no VARCHAR(50) REFERENCES jobs(job_no),
    exported_by INTEGER REFERENCES users(user_id),
    export_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    export_type VARCHAR(50), -- 'full', 'category', 'filtered'
    category VARCHAR(50), -- PIPE, FLANGE, VALVE 등
    material_count INTEGER,
    file_name VARCHAR(255),
    notes TEXT,
    -- 메타데이터
    filters_applied JSONB, -- 적용된 필터 조건들
    export_options JSONB -- 내보내기 옵션들
);

-- 2. 내보낸 자재 상세 (어떤 자재들이 내보내졌는지 추적)
CREATE TABLE IF NOT EXISTS exported_materials (
    id SERIAL PRIMARY KEY,
    export_id INTEGER REFERENCES excel_export_history(export_id) ON DELETE CASCADE,
    material_id INTEGER REFERENCES materials(id),
    purchase_status VARCHAR(50) DEFAULT 'pending', -- pending, requested, ordered, received, cancelled
    purchase_request_no VARCHAR(100), -- 구매요청 번호
    purchase_order_no VARCHAR(100), -- 구매주문 번호
    requested_date TIMESTAMP,
    ordered_date TIMESTAMP,
    expected_date DATE,
    received_date TIMESTAMP,
    quantity_exported INTEGER, -- 내보낸 수량
    quantity_ordered INTEGER, -- 주문 수량
    quantity_received INTEGER, -- 입고 수량
    unit_price DECIMAL(15, 2),
    total_price DECIMAL(15, 2),
    vendor_name VARCHAR(255),
    notes TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_by INTEGER REFERENCES users(user_id)
);

-- 3. 구매 상태 이력 (상태 변경 추적)
CREATE TABLE IF NOT EXISTS purchase_status_history (
    history_id SERIAL PRIMARY KEY,
    exported_material_id INTEGER REFERENCES exported_materials(id) ON DELETE CASCADE,
    material_id INTEGER REFERENCES materials(id),
    previous_status VARCHAR(50),
    new_status VARCHAR(50),
    changed_by INTEGER REFERENCES users(user_id),
    changed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    reason TEXT,
    metadata JSONB -- 추가 정보 (예: 문서 번호, 승인자 등)
);

-- 4. 구매 문서 관리
CREATE TABLE IF NOT EXISTS purchase_documents (
    document_id SERIAL PRIMARY KEY,
    export_id INTEGER REFERENCES excel_export_history(export_id),
    document_type VARCHAR(50), -- 'purchase_request', 'purchase_order', 'invoice', 'receipt'
    document_no VARCHAR(100),
    document_date DATE,
    file_path VARCHAR(500),
    uploaded_by INTEGER REFERENCES users(user_id),
    uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    notes TEXT
);

-- 인덱스 추가
CREATE INDEX IF NOT EXISTS idx_export_history_file_id ON excel_export_history(file_id);
CREATE INDEX IF NOT EXISTS idx_export_history_job_no ON excel_export_history(job_no);
CREATE INDEX IF NOT EXISTS idx_export_history_date ON excel_export_history(export_date);
CREATE INDEX IF NOT EXISTS idx_exported_materials_export_id ON exported_materials(export_id);
CREATE INDEX IF NOT EXISTS idx_exported_materials_material_id ON exported_materials(material_id);
CREATE INDEX IF NOT EXISTS idx_exported_materials_status ON exported_materials(purchase_status);
CREATE INDEX IF NOT EXISTS idx_exported_materials_pr_no ON exported_materials(purchase_request_no);
CREATE INDEX IF NOT EXISTS idx_exported_materials_po_no ON exported_materials(purchase_order_no);
CREATE INDEX IF NOT EXISTS idx_purchase_history_material ON purchase_status_history(material_id);
CREATE INDEX IF NOT EXISTS idx_purchase_history_date ON purchase_status_history(changed_at);

-- 뷰 생성: 구매 상태별 자재 현황
CREATE OR REPLACE VIEW v_purchase_status_summary AS
SELECT 
    em.purchase_status,
    COUNT(DISTINCT em.material_id) as material_count,
    COUNT(DISTINCT em.export_id) as export_count,
    SUM(em.quantity_exported) as total_quantity_exported,
    SUM(em.quantity_ordered) as total_quantity_ordered,
    SUM(em.quantity_received) as total_quantity_received,
    SUM(em.total_price) as total_amount,
    MAX(em.updated_at) as last_updated
FROM exported_materials em
GROUP BY em.purchase_status;

-- 뷰 생성: 자재별 최신 구매 상태
CREATE OR REPLACE VIEW v_material_latest_purchase_status AS
SELECT DISTINCT ON (m.id)
    m.id as material_id,
    m.original_description,
    m.classified_category,
    em.purchase_status,
    em.purchase_request_no,
    em.purchase_order_no,
    em.vendor_name,
    em.expected_date,
    em.quantity_ordered,
    em.quantity_received,
    em.updated_at as status_updated_at,
    eeh.export_date as last_exported_date
FROM materials m
LEFT JOIN exported_materials em ON m.id = em.material_id
LEFT JOIN excel_export_history eeh ON em.export_id = eeh.export_id
ORDER BY m.id, em.updated_at DESC;

-- 트리거: updated_at 자동 업데이트
CREATE OR REPLACE FUNCTION update_exported_materials_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER update_exported_materials_updated_at_trigger
BEFORE UPDATE ON exported_materials
FOR EACH ROW
EXECUTE FUNCTION update_exported_materials_updated_at();

-- 코멘트 추가
COMMENT ON TABLE excel_export_history IS '엑셀 내보내기 이력 관리';
COMMENT ON TABLE exported_materials IS '내보낸 자재의 구매 상태 추적';
COMMENT ON TABLE purchase_status_history IS '구매 상태 변경 이력';
COMMENT ON TABLE purchase_documents IS '구매 관련 문서 관리';
COMMENT ON COLUMN exported_materials.purchase_status IS 'pending: 구매신청 전, requested: 구매신청, ordered: 구매주문, received: 입고완료, cancelled: 취소';
