#!/usr/bin/env node

const { PrismaClient } = require('@prisma/client');

async function testConnection() {
  const prisma = new PrismaClient();
  
  console.log('🔍 Testing database connection...\n');
  
  try {
    // Test basic connection
    console.log('📡 Attempting to connect to database...');
    await prisma.$connect();
    console.log('✅ Database connection successful!\n');
    
    // Test if tables exist
    console.log('🗄️  Checking database schema...');
    
    try {
      const userCount = await prisma.user.count();
      console.log(`✅ Users table exists (${userCount} records)`);
    } catch (error) {
      console.log('❌ Users table not found - need to run migrations');
    }
    
    try {
      const promptCount = await prisma.prompt.count();
      console.log(`✅ Prompts table exists (${promptCount} records)`);
    } catch (error) {
      console.log('❌ Prompts table not found - need to run migrations');
    }
    
    try {
      const tagCount = await prisma.promptTag.count();
      console.log(`✅ PromptTag table exists (${tagCount} records)`);
    } catch (error) {
      console.log('❌ PromptTag table not found - need to run migrations');
    }
    
  } catch (error) {
    console.error('❌ Database connection failed:');
    console.error('Error:', error.message);
    
    if (error.message.includes("Can't reach database server")) {
      console.log('\n💡 Possible solutions:');
      console.log('1. Check if your Supabase project is active');
      console.log('2. Verify your DATABASE_URL in .env file');
      console.log('3. Check if your IP is allowed in Supabase settings');
      console.log('4. Ensure your Supabase project is not paused');
    }
    
    if (error.message.includes('does not exist')) {
      console.log('\n💡 Run database migrations:');
      console.log('   npm run db:push');
    }
    
    process.exit(1);
  } finally {
    await prisma.$disconnect();
  }
  
  console.log('\n🎉 Database connection test completed successfully!');
}

testConnection();
