// scripts/delete-test-articles.ts
import { drizzle } from 'drizzle-orm/neon-serverless';
import { Pool } from '@neondatabase/serverless';
import { blogPosts } from '../shared/schema';
import { like, or, eq, and } from 'drizzle-orm';
import * as dotenv from 'dotenv';

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

const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const db = drizzle(pool);
const SITE_ID = 'ten-sura-game.com';

async function deleteTestArticles() {
  try {
    console.log('🗑️  Starting test articles cleanup...\n');

    // First, let's see what we're about to delete
    const testArticles = await db
      .select({
        id: blogPosts.id,
        externalId: blogPosts.externalId,
        title: blogPosts.title,
        slug: blogPosts.slug,
      })
      .from(blogPosts)
      .where(
        and(
          or(
            like(blogPosts.externalId, 'test-%'),
            like(blogPosts.title, '%Test Article%'),
            like(blogPosts.title, '%API Verification%')
          ),
          eq(blogPosts.siteId, SITE_ID)
        )
      );

    if (testArticles.length === 0) {
      console.log('✨ No test articles found in the database. Database is already clean!');
      process.exit(0);
    }

    console.log(`Found ${testArticles.length} test articles to delete:\n`);
    testArticles.forEach((article, index) => {
      console.log(`${index + 1}. [${article.externalId}] ${article.title}`);
    });

    console.log('\n🔥 Deleting test articles...\n');

    // Delete all test articles
    const result = await db
      .delete(blogPosts)
      .where(
        and(
          or(
            like(blogPosts.externalId, 'test-%'),
            like(blogPosts.title, '%Test Article%'),
            like(blogPosts.title, '%API Verification%')
          ),
          eq(blogPosts.siteId, SITE_ID)
        )
      )
      .returning({ deletedId: blogPosts.id, deletedTitle: blogPosts.title });

    console.log(`✅ Successfully deleted ${result.length} test articles:\n`);
    result.forEach((article, index) => {
      console.log(`${index + 1}. ${article.deletedTitle}`);
    });

    console.log('\n✨ Test articles cleanup completed successfully!');
    
    await pool.end();
    process.exit(0);
  } catch (error) {
    console.error('❌ Error deleting test articles:', error);
    await pool.end();
    process.exit(1);
  }
}

deleteTestArticles();
