import { S3Client, ListObjectsV2Command } from '@aws-sdk/client-s3';
import dotenv from 'dotenv';

dotenv.config();

async function listR2Objects() {
	const accountId = process.env.CLOUDFLARE_ACCOUNT_ID;
	const accessKeyId = process.env.CLOUDFLARE_R2_ACCESS_KEY_ID;
	const secretAccessKey = process.env.CLOUDFLARE_R2_SECRET_ACCESS_KEY;
	const bucket = process.env.CLOUDFLARE_R2_BUCKET_NAME || 'neoad';
	
	if (!accountId || !accessKeyId || !secretAccessKey) {
		throw new Error('Variables d\'environnement Cloudflare R2 manquantes');
	}
	
	const client = new S3Client({
		region: 'auto',
		endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
		credentials: {
			accessKeyId,
			secretAccessKey
		}
	});

	console.log(`📦 Listing objects in bucket: ${bucket}`);
	console.log(`   Searching for all objects...\n`);

	const command = new ListObjectsV2Command({
		Bucket: bucket,
		MaxKeys: 100
	});

	const response = await client.send(command);

	if (response.Contents && response.Contents.length > 0) {
		console.log(`✅ Found ${response.Contents.length} object(s):\n`);
		for (const obj of response.Contents) {
			console.log(`   ${obj.Key} (${obj.Size} bytes)`);
		}
	} else {
		console.log('❌ No objects found with this prefix');
		
		// Try listing all objects at root
		console.log('\n📦 Trying to list all objects at root...\n');
		const rootCommand = new ListObjectsV2Command({
			Bucket: bucket,
			MaxKeys: 20
		});
		const rootResponse = await client.send(rootCommand);
		
		if (rootResponse.Contents && rootResponse.Contents.length > 0) {
			console.log(`Found ${rootResponse.Contents.length} object(s) at root:`);
			for (const obj of rootResponse.Contents) {
				console.log(`   ${obj.Key}`);
			}
		} else {
			console.log('No objects found at root either');
		}
	}
}

listR2Objects().catch(console.error);
