/**
 * Populate Mission SEO Fields Script
 * 
 * This script auto-generates seo_title and seo_description for all missions
 * that don't have them populated yet.
 * 
 * Run with: node src/scripts/populate_mission_seo.js
 */

const db = require('../db');

async function populateMissionSEO() {
    console.log('🔍 Checking missions for missing SEO fields...\n');

    try {
        // Get all operations missing SEO data
        const result = await db.query(`
            SELECT id, title, apt_group, description, slug
            FROM operations 
            WHERE (seo_title IS NULL OR seo_title = '') 
               OR (seo_description IS NULL OR seo_description = '')
        `);

        if (result.rows.length === 0) {
            console.log('✅ All missions already have SEO fields populated!');
            return;
        }

        console.log(`📋 Found ${result.rows.length} missions needing SEO updates:\n`);

        for (const op of result.rows) {
            // Generate SEO title: "Operation Title | APT Group Training"
            const seoTitle = `${op.title} | ${op.apt_group || 'APT'} Training Simulation`;
            
            // Generate SEO description: First 150 chars + call to action
            let seoDesc = op.description || '';
            seoDesc = seoDesc.substring(0, 140).trim();
            if (seoDesc.length > 0 && !seoDesc.endsWith('.')) {
                seoDesc += '...';
            }
            seoDesc += ' Train as a SOC analyst with this hands-on simulation.';

            // Update the database
            await db.query(`
                UPDATE operations 
                SET seo_title = $1, 
                    seo_description = $2
                WHERE id = $3
            `, [seoTitle, seoDesc, op.id]);

            console.log(`✅ Updated: ${op.title}`);
            console.log(`   SEO Title: ${seoTitle.substring(0, 50)}...`);
            console.log(`   SEO Desc:  ${seoDesc.substring(0, 50)}...\n`);
        }

        console.log(`\n🎉 Successfully updated ${result.rows.length} missions with SEO data!`);

    } catch (error) {
        console.error('❌ Error populating SEO fields:', error);
        process.exit(1);
    } finally {
        process.exit(0);
    }
}

populateMissionSEO();
