// scripts/check-articles.ts
import { drizzle } from 'drizzle-orm/neon-serverless';
import { Pool } from '@neondatabase/serverless';
import { blogPosts } from '../shared/schema';
import { count, eq } 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 checkArticles() {
  try {
    console.log('📊 Checking database articles...\n');

    // Get total count
    const totalResult = await db
      .select({ count: count() })
      .from(blogPosts)
      .where(eq(blogPosts.siteId, SITE_ID));
    
    const totalCount = totalResult[0]?.count || 0;

    console.log(`Total articles for ${SITE_ID} in database: ${totalCount}\n`);

    if (totalCount > 0) {
      // Show all articles
      const articles = await db
        .select({
          id: blogPosts.id,
          externalId: blogPosts.externalId,
          title: blogPosts.title,
          slug: blogPosts.slug,
          isActive: blogPosts.isActive,
        })
        .from(blogPosts)
        .where(eq(blogPosts.siteId, SITE_ID));

      console.log('Articles found:\n');
      articles.forEach((article, index) => {
        console.log(`${index + 1}. [${article.externalId}] ${article.title}`);
        console.log(`   Slug: ${article.slug}`);
        console.log(`   Active: ${article.isActive}\n`);
      });
    } else {
      console.log('✨ Database is empty. Ready for real articles from Bubble!');
    }

    await pool.end();
    process.exit(0);
  } catch (error) {
    console.error('❌ Error checking articles:', error);
    await pool.end();
    process.exit(1);
  }
}

checkArticles();
