// Migration: Add knowledge_base table for storing documentation and policies

const sqlite3 = require('sqlite3').verbose();
const path = require('path');

const dbPath = path.join(__dirname, '..', 'cve_database.db');
const db = new sqlite3.Database(dbPath);

console.log('Running migration: add_knowledge_base_table');

db.serialize(() => {
  db.run(`
    CREATE TABLE IF NOT EXISTS knowledge_base (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      title VARCHAR(255) NOT NULL,
      slug VARCHAR(255) UNIQUE NOT NULL,
      description TEXT,
      category VARCHAR(100),
      file_path VARCHAR(500),
      file_name VARCHAR(255),
      file_type VARCHAR(50),
      file_size INTEGER,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      created_by INTEGER,
      FOREIGN KEY (created_by) REFERENCES users(id)
    )
  `, (err) => {
    if (err) {
      console.error('Error creating knowledge_base table:', err);
      process.exit(1);
    }
    console.log('✓ Created knowledge_base table');
  });

  db.run(`
    CREATE INDEX IF NOT EXISTS idx_knowledge_base_slug
    ON knowledge_base(slug)
  `, (err) => {
    if (err) {
      console.error('Error creating slug index:', err);
      process.exit(1);
    }
    console.log('✓ Created index on slug');
  });

  db.run(`
    CREATE INDEX IF NOT EXISTS idx_knowledge_base_category
    ON knowledge_base(category)
  `, (err) => {
    if (err) {
      console.error('Error creating category index:', err);
      process.exit(1);
    }
    console.log('✓ Created index on category');
  });

  db.run(`
    CREATE INDEX IF NOT EXISTS idx_knowledge_base_created_at
    ON knowledge_base(created_at DESC)
  `, (err) => {
    if (err) {
      console.error('Error creating created_at index:', err);
      process.exit(1);
    }
    console.log('✓ Created index on created_at');
    console.log('\nMigration completed successfully!');
    db.close();
  });
});
