-- 구매신청 관리 테이블

-- 구매신청 그룹 (같이 신청한 항목들의 묶음)
CREATE TABLE IF NOT EXISTS purchase_requests (
    request_id SERIAL PRIMARY KEY,
    request_no VARCHAR(50) UNIQUE, -- PR-20241014-001 형식
    file_id INTEGER REFERENCES files(id),
    job_no VARCHAR(50) REFERENCES jobs(job_no),
    category VARCHAR(50),
    material_count INTEGER,
    excel_file_path VARCHAR(500), -- 저장된 엑셀 파일 경로
    requested_by INTEGER REFERENCES users(user_id),
    requested_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    status VARCHAR(20) DEFAULT 'requested', -- requested, ordered, received
    notes TEXT
);

-- 구매신청 자재 상세
CREATE TABLE IF NOT EXISTS purchase_request_items (
    item_id SERIAL PRIMARY KEY,
    request_id INTEGER REFERENCES purchase_requests(request_id) ON DELETE CASCADE,
    material_id INTEGER REFERENCES materials(id),
    quantity INTEGER,
    unit VARCHAR(20),
    user_requirement TEXT,
    is_ordered BOOLEAN DEFAULT FALSE,
    is_received BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 인덱스
CREATE INDEX IF NOT EXISTS idx_purchase_requests_file_id ON purchase_requests(file_id);
CREATE INDEX IF NOT EXISTS idx_purchase_requests_job_no ON purchase_requests(job_no);
CREATE INDEX IF NOT EXISTS idx_purchase_requests_status ON purchase_requests(status);
CREATE INDEX IF NOT EXISTS idx_purchase_request_items_request_id ON purchase_request_items(request_id);
CREATE INDEX IF NOT EXISTS idx_purchase_request_items_material_id ON purchase_request_items(material_id);

-- 뷰: 구매신청된 자재 ID 목록
CREATE OR REPLACE VIEW v_requested_material_ids AS
SELECT DISTINCT material_id
FROM purchase_request_items;

COMMENT ON TABLE purchase_requests IS '구매신청 그룹 관리';
COMMENT ON TABLE purchase_request_items IS '구매신청 자재 상세';
