export default defineEventHandler(async (event) => {
  try {
    const config = useRuntimeConfig().minio;
    
    // Log configuration (without secrets)
    const configInfo = {
      endPoint: config.endPoint,
      port: config.port,
      useSSL: config.useSSL,
      bucketName: config.bucketName,
      hasAccessKey: !!config.accessKey,
      hasSecretKey: !!config.secretKey,
      accessKeyLength: config.accessKey?.length || 0,
      secretKeyLength: config.secretKey?.length || 0,
    };
    
    console.log('Testing MinIO connection with config:', configInfo);
    
    // Import MinIO client
    const { Client } = await import('minio');
    
    // Create client
    const client = new Client({
      endPoint: config.endPoint,
      port: parseInt(config.port),
      useSSL: config.useSSL,
      accessKey: config.accessKey,
      secretKey: config.secretKey,
    });
    
    // Test bucket exists
    const bucketExists = await client.bucketExists(config.bucketName);
    console.log(`Bucket ${config.bucketName} exists:`, bucketExists);
    
    // If bucket doesn't exist, try to create it
    if (!bucketExists) {
      console.log(`Attempting to create bucket ${config.bucketName}`);
      await client.makeBucket(config.bucketName, 'us-east-1');
      console.log(`Bucket ${config.bucketName} created successfully`);
    }
    
    // List buckets to verify connection
    const buckets = await client.listBuckets();
    console.log('Available buckets:', buckets.map(b => b.name));
    
    return {
      success: true,
      connection: 'successful',
      config: configInfo,
      bucketExists,
      availableBuckets: buckets.map(b => b.name),
    };
  } catch (error: any) {
    console.error('MinIO connection test failed:', error);
    return {
      success: false,
      error: error.message,
      stack: error.stack,
      code: error.code,
    };
  }
});
