-- =============================================
-- 文档管理模块 DDL
-- =============================================

-- 文档分类表
CREATE TABLE IF NOT EXISTS doc_category (
    id BIGSERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    parent_id BIGINT DEFAULT 0,
    sort INT DEFAULT 0,
    deleted SMALLINT DEFAULT 0,
    create_time TIMESTAMP DEFAULT NOW()
);
COMMENT ON TABLE doc_category IS '文档分类表';

-- 文档主表
CREATE TABLE IF NOT EXISTS doc (
    id BIGSERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    file_type VARCHAR(20),
    file_size BIGINT DEFAULT 0,
    storage_path VARCHAR(500) NOT NULL,
    category_id BIGINT REFERENCES doc_category(id),
    tags VARCHAR(500),
    current_version INT DEFAULT 1,
    uploader_id BIGINT,
    uploader_name VARCHAR(50),
    access_level SMALLINT DEFAULT 0,
    dept_id BIGINT,
    download_count INT DEFAULT 0,
    search_text TEXT,
    deleted SMALLINT DEFAULT 0,
    create_time TIMESTAMP DEFAULT NOW(),
    update_time TIMESTAMP DEFAULT NOW()
);
COMMENT ON TABLE doc IS '文档主表';
COMMENT ON COLUMN doc.access_level IS '权限级别: 0-公开 1-部门可见 2-仅自己';

-- 文档版本表
CREATE TABLE IF NOT EXISTS doc_version (
    id BIGSERIAL PRIMARY KEY,
    doc_id BIGINT NOT NULL REFERENCES doc(id),
    version INT NOT NULL,
    storage_path VARCHAR(500) NOT NULL,
    file_size BIGINT DEFAULT 0,
    change_log VARCHAR(500),
    uploader_id BIGINT,
    uploader_name VARCHAR(50),
    create_time TIMESTAMP DEFAULT NOW()
);
COMMENT ON TABLE doc_version IS '文档版本表';

-- 索引
CREATE INDEX IF NOT EXISTS idx_doc_category ON doc(category_id);
CREATE INDEX IF NOT EXISTS idx_doc_uploader ON doc(uploader_id);
CREATE INDEX IF NOT EXISTS idx_doc_dept ON doc(dept_id);
CREATE INDEX IF NOT EXISTS idx_doc_file_type ON doc(file_type);
CREATE INDEX IF NOT EXISTS idx_doc_search_text ON doc USING gin(to_tsvector('simple', COALESCE(search_text, '')));
CREATE INDEX IF NOT EXISTS idx_doc_version_doc_id ON doc_version(doc_id);

-- 默认分类
INSERT INTO doc_category (name, parent_id, sort) VALUES
('技术规范', 0, 1),
('操作手册', 0, 2),
('设计图纸', 0, 3),
('合同文件', 0, 4),
('会议纪要', 0, 5)
ON CONFLICT DO NOTHING;
