// Migration: Add archer_templates table for the Archer Template Library feature
const pool = require('../db');

async function run() {
    console.log('Starting archer_templates table migration...');
    try {
        await pool.query(`
            CREATE TABLE IF NOT EXISTS archer_templates (
                id SERIAL PRIMARY KEY,
                vendor VARCHAR(100) NOT NULL,
                platform VARCHAR(100) NOT NULL,
                model VARCHAR(100) NOT NULL,
                environment_overview TEXT NOT NULL DEFAULT '',
                segmentation TEXT NOT NULL DEFAULT '',
                mitigating_controls TEXT NOT NULL DEFAULT '',
                additional_info TEXT NOT NULL DEFAULT '',
                charter_network_banner TEXT NOT NULL DEFAULT '',
                data_classification TEXT NOT NULL DEFAULT '',
                charter_network TEXT NOT NULL DEFAULT '',
                additional_access_list TEXT NOT NULL DEFAULT '',
                created_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
                created_at TIMESTAMPTZ DEFAULT NOW(),
                updated_at TIMESTAMPTZ DEFAULT NOW()
            )
        `);
        console.log('✓ archer_templates table created (or already exists)');

        // Case-insensitive uniqueness on trimmed vendor/platform/model
        await pool.query(`
            CREATE UNIQUE INDEX IF NOT EXISTS idx_archer_templates_unique_combo
            ON archer_templates (LOWER(TRIM(vendor)), LOWER(TRIM(platform)), LOWER(TRIM(model)))
        `);
        console.log('✓ idx_archer_templates_unique_combo index created (or already exists)');

        // Indexes for list query performance
        await pool.query(`
            CREATE INDEX IF NOT EXISTS idx_archer_templates_vendor
            ON archer_templates(vendor)
        `);
        console.log('✓ idx_archer_templates_vendor index created (or already exists)');

        await pool.query(`
            CREATE INDEX IF NOT EXISTS idx_archer_templates_platform
            ON archer_templates(platform)
        `);
        console.log('✓ idx_archer_templates_platform index created (or already exists)');

        console.log('Migration complete.');
    } catch (err) {
        console.error('Migration failed:', err.message);
        throw err;
    }
}

module.exports = { run };

// Self-execute when run directly
if (require.main === module) {
    run().then(() => process.exit(0)).catch(() => process.exit(1));
}
