// Migration: Add ivanti_counts_history table
//
// Stores a snapshot of open/closed Ivanti finding counts on every sync.
// Unlike ivanti_counts_cache (single-row, always overwritten), this table
// accumulates all snapshots so time-series charts can be built from it.
//
// The GET /api/ivanti/findings/counts/history endpoint aggregates these rows
// to the last snapshot per calendar day using a ROW_NUMBER window function.
//
// NOTE: This table is also created automatically at server startup via
// CREATE TABLE IF NOT EXISTS in initTables() (ivantiFindings.js).
// This script is provided for manual setup on fresh installs and for
// documentation consistency with other migration files.
//
// Usage: node backend/migrations/add_ivanti_counts_history_table.js

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 ivanti_counts_history migration...');

db.serialize(() => {
    db.run(`
        CREATE TABLE IF NOT EXISTS ivanti_counts_history (
            id           INTEGER PRIMARY KEY AUTOINCREMENT,
            open_count   INTEGER NOT NULL,
            closed_count INTEGER NOT NULL,
            recorded_at  DATETIME DEFAULT CURRENT_TIMESTAMP
        )
    `, (err) => {
        if (err) console.error('Error creating ivanti_counts_history table:', err);
        else console.log('✓ ivanti_counts_history table created (or already exists)');
    });
});

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