// scripts/delete-mock-data.ts
import { drizzle } from 'drizzle-orm/neon-serverless';
import { Pool } from '@neondatabase/serverless';
import { blogPosts } from '../shared/schema';
import { like, eq, and, sql } 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 deleteMockData() {
  try {
    console.log('🗑️  Starting mock data cleanup...\n');

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

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

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

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

    // Delete all articles where externalId starts with 'mock-'
    const result = await db
      .delete(blogPosts)
      .where(
        and(
          like(blogPosts.externalId, 'mock-%'),
          eq(blogPosts.siteId, SITE_ID)
        )
      )
      .returning({ deletedId: blogPosts.id, deletedTitle: blogPosts.title });

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

    console.log('\n✨ Mock data cleanup completed successfully!');
    console.log('💡 Your database now only contains real articles from Bubble.');
    
    await pool.end();
    process.exit(0);
  } catch (error) {
    console.error('❌ Error deleting mock data:', error);
    await pool.end();
    process.exit(1);
  }
}

deleteMockData();
