import PocketBase from 'pocketbase';

async function deleteAllCollections() {
  const pb = new PocketBase('http://localhost:8090');

  // Authenticate as superuser (required for deleting collections)
  try {
    await pb.collection("_superusers").authWithPassword('admin@example.com', 'azsxdcazsxdc');
    console.log('Authenticated as superuser');
  } catch (error) {
    console.error('Failed to authenticate as superuser:', error.message);
    throw error;
  }

  try {
    console.log('Fetching all collections...');
    const collections = await pb.collections.getFullList();

    console.log(`Found ${collections.length} collections to delete`);

    for (const collection of collections) {
      try {
        console.log(`Deleting records from collection: ${collection.name}`);

        // Get all records from the collection
        const records = await pb.collection(collection.name).getFullList();
        console.log(`  Found ${records.length} records in ${collection.name}`);

        // Delete all records
        for (const record of records) {
          await pb.collection(collection.name).delete(record.id);
        }
        console.log(`  Deleted all records from ${collection.name}`);

        // Delete the collection itself
        await pb.collections.delete(collection.id);
        console.log(`✓ Deleted collection: ${collection.name}`);

      } catch (error) {
        console.error(`Error deleting collection ${collection.name}:`, error.message);
      }
    }

    console.log('All collections and records deleted successfully');

  } catch (error) {
    console.error('Error fetching collections:', error);
    throw error;
  }
}

// Check if this script is being run directly
if (import.meta.url === `file://${process.argv[1]}`) {
  deleteAllCollections()
    .then(() => {
      console.log('Script completed successfully');
      process.exit(0);
    })
    .catch((error) => {
      console.error('Script failed:', error);
      process.exit(1);
    });
}

export { deleteAllCollections };