import 'dotenv/config';
import mongoose from 'mongoose';
import WebsiteSubmission from './models/websiteSubmission.js';

async function checkSubmissions() {
  try {
    console.log('🔌 Connecting to MongoDB...');
    
    await mongoose.connect(process.env.MONGO_URI, {
      retryWrites: true,
      w: 'majority',
    });

    console.log('✅ Connected to MongoDB\n');

    // Get all submissions
    const submissions = await WebsiteSubmission.find({})
      .select('Title Submitted_URL URL paymentOrderID createdAt')
      .sort({ createdAt: -1 });

    console.log(`📊 Total submissions in database: ${submissions.length}\n`);

    if (submissions.length > 0) {
      console.log('📝 Recent submissions:');
      console.log('═══════════════════════════════════════════════════════════════');
      submissions.forEach((sub, index) => {
        console.log(`${index + 1}. ${sub.Title}`);
        console.log(`   Website URL: ${sub.Submitted_URL}`);
        console.log(`   Profile URL: ${sub.URL}`);
        console.log(`   Payment ID: ${sub.paymentOrderID}`);
        console.log(`   Created: ${sub.createdAt.toLocaleString()}`);
        console.log('───────────────────────────────────────────────────────────────');
      });

      console.log('\n⚠️  To delete ALL submissions, run:');
      console.log('   node check-submissions.js delete-all');
      console.log('\n⚠️  To delete last 24 hours, run:');
      console.log('   node check-submissions.js delete-24h');
    } else {
      console.log('✅ No submissions found in database - you can submit without issues!');
    }

    // Check for delete command
    const action = process.argv[2];
    
    if (action === 'delete-all') {
      console.log('\n⚠️  WARNING: Deleting ALL submissions...');
      const result = await WebsiteSubmission.deleteMany({});
      console.log(`✅ Deleted ${result.deletedCount} submissions`);
    } else if (action === 'delete-24h') {
      const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
      console.log('\n⚠️  Deleting submissions from last 24 hours...');
      const result = await WebsiteSubmission.deleteMany({
        createdAt: { $gte: oneDayAgo }
      });
      console.log(`✅ Deleted ${result.deletedCount} submissions`);
    }

    await mongoose.connection.close();
    console.log('\n✅ Disconnected from MongoDB');
    process.exit(0);

  } catch (error) {
    console.error('\n❌ Error:', error.message);
    process.exit(1);
  }
}

checkSubmissions();
