import { requireAuth } from '~/server/utils/auth';
import { getMinioClient } from '~/server/utils/minio';

export default defineEventHandler(async (event) => {
  // Check authentication (x-tag header OR Keycloak session)
  await requireAuth(event);

  try {
    const query = getQuery(event);
    const { interestId } = query;
    
    const client = getMinioClient();
    
    // Test 1: Check if client-emails bucket exists
    const buckets = await client.listBuckets();
    const clientEmailsBucket = buckets.find(b => b.name === 'client-emails');
    
    if (!clientEmailsBucket) {
      // Try to create the bucket
      await client.makeBucket('client-emails', 'us-east-1');
    }
    
    // Test 2: List files in the bucket
    const files: any[] = [];
    const prefix = interestId ? `interest-${interestId}/` : '';
    const stream = client.listObjectsV2('client-emails', prefix, true);
    
    await new Promise((resolve, reject) => {
      stream.on('data', (obj) => {
        if (obj && obj.name) {
          files.push({
            name: obj.name,
            size: obj.size || 0,
            lastModified: obj.lastModified
          });
        }
      });
      stream.on('error', reject);
      stream.on('end', resolve);
    });
    
    // Test 3: Try to write a test file
    const testData = {
      test: true,
      timestamp: new Date().toISOString(),
      message: 'MinIO bucket test'
    };
    
    const testObjectName = `test/${Date.now()}-test.json`;
    const buffer = Buffer.from(JSON.stringify(testData, null, 2));
    
    await client.putObject('client-emails', testObjectName, buffer, buffer.length, {
      'Content-Type': 'application/json',
    });
    
    // Test 4: Try to read the test file back
    const readStream = await client.getObject('client-emails', testObjectName);
    let readData = '';
    
    await new Promise((resolve, reject) => {
      readStream.on('data', (chunk) => {
        readData += chunk;
      });
      readStream.on('end', resolve);
      readStream.on('error', reject);
    });
    
    // Clean up test file
    await client.removeObject('client-emails', testObjectName);
    
    return {
      success: true,
      bucketExists: !!clientEmailsBucket,
      bucketCreated: !clientEmailsBucket,
      filesInBucket: files.length,
      files: files.slice(0, 10), // Show first 10 files
      writeTestPassed: true,
      readTestPassed: JSON.parse(readData).test === true
    };
  } catch (error) {
    console.error('MinIO bucket test failed:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Unknown error',
      details: error
    };
  }
});
