// scripts/insert-mock-data.ts
// Script to insert 10 mock articles into the database

import { config } from 'dotenv';
import { readFileSync } from 'fs';
import { join } from 'path';
import { neon } from '@neondatabase/serverless';

// Load environment variables
config({ path: '.env.local' });

async function insertMockData() {
  const databaseUrl = process.env.DATABASE_URL;

  if (!databaseUrl) {
    console.error('❌ DATABASE_URL environment variable is not set');
    process.exit(1);
  }

  console.log('🚀 Starting mock data insertion...');

  const sql = neon(databaseUrl);

  try {
    // Read the migration file
    const migrationPath = join(process.cwd(), 'migrations', '007_insert_mock_articles.sql');
    const migrationSQL = readFileSync(migrationPath, 'utf-8');

    console.log('📄 Executing migration: 007_insert_mock_articles.sql');

    // Split by INSERT statements and filter out comments and empty lines
    const statements = migrationSQL
      .split(/(?=INSERT INTO blog_posts)/g)
      .map(stmt => stmt.trim())
      .filter(stmt => stmt.startsWith('INSERT'))
      .map(stmt => {
        // Remove any trailing comments or other SQL commands
        const lines = stmt.split('\n');
        const insertLines = [];
        for (const line of lines) {
          if (line.trim().startsWith('--') || line.trim().startsWith('COMMENT')) {
            break;
          }
          insertLines.push(line);
        }
        return insertLines.join('\n').trim();
      })
      .filter(stmt => stmt.length > 0);

    console.log(`📊 Found ${statements.length} INSERT statements`);

    // Execute each INSERT statement separately
    for (let i = 0; i < statements.length; i++) {
      const statement = statements[i];
      console.log(`   Inserting article ${i + 1}/${statements.length}...`);
      await sql(statement);
    }

    console.log('✅ Mock data inserted successfully!');
    console.log('📊 Inserted 10 articles:');
    console.log('   - スポーツクラブ運営: 2 articles');
    console.log('   - 社会人: 2 articles');
    console.log('   - ジュニア: 2 articles');
    console.log('   - 女子チーム: 2 articles');
    console.log('   - モチベーション管理: 2 articles');
    console.log('');
    console.log('🎉 You can now test your application with real data!');

  } catch (error) {
    console.error('❌ Error inserting mock data:', error);
    process.exit(1);
  }
}

insertMockData();
