// Migration: Add created_at / updated_at columns to archer_tickets
//
// SQLite does not support ALTER TABLE ADD COLUMN IF NOT EXISTS, so we check
// PRAGMA table_info first and only add the column when it is absent.
//
// Run on any instance where archer_tickets was created before these columns
// were added to the schema (symptoms: every /api/archer-tickets call → 500).
//
// Usage: node backend/migrations/add_archer_tickets_timestamps.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 archer_tickets timestamp migration...');

db.all('PRAGMA table_info(archer_tickets)', [], (err, columns) => {
    if (err) {
        console.error('Error reading table info:', err);
        return db.close();
    }

    const names = columns.map(c => c.name);

    db.serialize(() => {
        if (!names.includes('created_at')) {
            db.run(
                `ALTER TABLE archer_tickets ADD COLUMN created_at DATETIME DEFAULT CURRENT_TIMESTAMP`,
                (err) => {
                    if (err) console.error('Error adding created_at:', err);
                    else console.log('✓ created_at column added');
                }
            );
        } else {
            console.log('✓ created_at already exists — skipping');
        }

        if (!names.includes('updated_at')) {
            db.run(
                `ALTER TABLE archer_tickets ADD COLUMN updated_at DATETIME DEFAULT CURRENT_TIMESTAMP`,
                (err) => {
                    if (err) console.error('Error adding updated_at:', err);
                    else console.log('✓ updated_at column added');
                }
            );
        } else {
            console.log('✓ updated_at already exists — skipping');
        }
    });

    db.close(() => {
        console.log('Migration complete. Restart the backend server.');
    });
});
