// Migration: Add archer_tickets table
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('Starting Archer tickets migration...');

db.serialize(() => {
  // Create archer_tickets table
  db.run(`
    CREATE TABLE IF NOT EXISTS archer_tickets (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      exc_number TEXT NOT NULL UNIQUE,
      archer_url TEXT,
      status TEXT DEFAULT 'Draft' CHECK(status IN ('Draft', 'Open', 'Under Review', 'Accepted')),
      cve_id TEXT NOT NULL,
      vendor TEXT NOT NULL,
      created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
      FOREIGN KEY (cve_id, vendor) REFERENCES cves(cve_id, vendor) ON DELETE CASCADE
    )
  `, (err) => {
    if (err) console.error('Error creating table:', err);
    else console.log('✓ archer_tickets table created');
  });

  // Create indexes
  db.run('CREATE INDEX IF NOT EXISTS idx_archer_tickets_cve ON archer_tickets(cve_id, vendor)', (err) => {
    if (err) console.error('Error creating CVE index:', err);
    else console.log('✓ CVE index created');
  });

  db.run('CREATE INDEX IF NOT EXISTS idx_archer_tickets_status ON archer_tickets(status)', (err) => {
    if (err) console.error('Error creating status index:', err);
    else console.log('✓ Status index created');
  });

  db.run('CREATE INDEX IF NOT EXISTS idx_archer_tickets_exc ON archer_tickets(exc_number)', (err) => {
    if (err) console.error('Error creating EXC number index:', err);
    else console.log('✓ EXC number index created');
  });

  console.log('✓ Indexes created');
});

db.close(() => {
  console.log('Migration complete!');
});
